PackageManagerService.java revision 011603ab76f55e1d8b62296ac48704b8b032d8e7
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
89import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90import static android.system.OsConstants.O_CREAT;
91import static android.system.OsConstants.O_RDWR;
92
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97import static com.android.internal.util.ArrayUtils.appendInt;
98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
106import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
107import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageManagerNative;
147import android.content.pm.IPackageMoveObserver;
148import android.content.pm.IPackageStatsObserver;
149import android.content.pm.InstantAppInfo;
150import android.content.pm.InstantAppRequest;
151import android.content.pm.InstantAppResolveInfo;
152import android.content.pm.InstrumentationInfo;
153import android.content.pm.IntentFilterVerificationInfo;
154import android.content.pm.KeySet;
155import android.content.pm.PackageCleanItem;
156import android.content.pm.PackageInfo;
157import android.content.pm.PackageInfoLite;
158import android.content.pm.PackageInstaller;
159import android.content.pm.PackageManager;
160import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
161import android.content.pm.PackageManagerInternal;
162import android.content.pm.PackageParser;
163import android.content.pm.PackageParser.ActivityIntentInfo;
164import android.content.pm.PackageParser.PackageLite;
165import android.content.pm.PackageParser.PackageParserException;
166import android.content.pm.PackageStats;
167import android.content.pm.PackageUserState;
168import android.content.pm.ParceledListSlice;
169import android.content.pm.PermissionGroupInfo;
170import android.content.pm.PermissionInfo;
171import android.content.pm.ProviderInfo;
172import android.content.pm.ResolveInfo;
173import android.content.pm.ServiceInfo;
174import android.content.pm.SharedLibraryInfo;
175import android.content.pm.Signature;
176import android.content.pm.UserInfo;
177import android.content.pm.VerifierDeviceIdentity;
178import android.content.pm.VerifierInfo;
179import android.content.pm.VersionedPackage;
180import android.content.pm.dex.DexMetadataHelper;
181import android.content.pm.dex.IArtManager;
182import android.content.res.Resources;
183import android.database.ContentObserver;
184import android.graphics.Bitmap;
185import android.hardware.display.DisplayManager;
186import android.net.Uri;
187import android.os.Binder;
188import android.os.Build;
189import android.os.Bundle;
190import android.os.Debug;
191import android.os.Environment;
192import android.os.Environment.UserEnvironment;
193import android.os.FileUtils;
194import android.os.Handler;
195import android.os.IBinder;
196import android.os.Looper;
197import android.os.Message;
198import android.os.Parcel;
199import android.os.ParcelFileDescriptor;
200import android.os.PatternMatcher;
201import android.os.Process;
202import android.os.RemoteCallbackList;
203import android.os.RemoteException;
204import android.os.ResultReceiver;
205import android.os.SELinux;
206import android.os.ServiceManager;
207import android.os.ShellCallback;
208import android.os.SystemClock;
209import android.os.SystemProperties;
210import android.os.Trace;
211import android.os.UserHandle;
212import android.os.UserManager;
213import android.os.UserManagerInternal;
214import android.os.storage.IStorageManager;
215import android.os.storage.StorageEventListener;
216import android.os.storage.StorageManager;
217import android.os.storage.StorageManagerInternal;
218import android.os.storage.VolumeInfo;
219import android.os.storage.VolumeRecord;
220import android.provider.Settings.Global;
221import android.provider.Settings.Secure;
222import android.security.KeyStore;
223import android.security.SystemKeyStore;
224import android.service.pm.PackageServiceDumpProto;
225import android.system.ErrnoException;
226import android.system.Os;
227import android.text.TextUtils;
228import android.text.format.DateUtils;
229import android.util.ArrayMap;
230import android.util.ArraySet;
231import android.util.Base64;
232import android.util.TimingsTraceLog;
233import android.util.DisplayMetrics;
234import android.util.EventLog;
235import android.util.ExceptionUtils;
236import android.util.Log;
237import android.util.LogPrinter;
238import android.util.MathUtils;
239import android.util.PackageUtils;
240import android.util.Pair;
241import android.util.PrintStreamPrinter;
242import android.util.Slog;
243import android.util.SparseArray;
244import android.util.SparseBooleanArray;
245import android.util.SparseIntArray;
246import android.util.Xml;
247import android.util.jar.StrictJarFile;
248import android.util.proto.ProtoOutputStream;
249import android.view.Display;
250
251import com.android.internal.R;
252import com.android.internal.annotations.GuardedBy;
253import com.android.internal.app.IMediaContainerService;
254import com.android.internal.app.ResolverActivity;
255import com.android.internal.content.NativeLibraryHelper;
256import com.android.internal.content.PackageHelper;
257import com.android.internal.logging.MetricsLogger;
258import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
259import com.android.internal.os.IParcelFileDescriptorFactory;
260import com.android.internal.os.RoSystemProperties;
261import com.android.internal.os.SomeArgs;
262import com.android.internal.os.Zygote;
263import com.android.internal.telephony.CarrierAppUtils;
264import com.android.internal.util.ArrayUtils;
265import com.android.internal.util.ConcurrentUtils;
266import com.android.internal.util.DumpUtils;
267import com.android.internal.util.FastPrintWriter;
268import com.android.internal.util.FastXmlSerializer;
269import com.android.internal.util.IndentingPrintWriter;
270import com.android.internal.util.Preconditions;
271import com.android.internal.util.XmlUtils;
272import com.android.server.AttributeCache;
273import com.android.server.DeviceIdleController;
274import com.android.server.EventLogTags;
275import com.android.server.FgThread;
276import com.android.server.IntentResolver;
277import com.android.server.LocalServices;
278import com.android.server.LockGuard;
279import com.android.server.ServiceThread;
280import com.android.server.SystemConfig;
281import com.android.server.SystemServerInitThreadPool;
282import com.android.server.Watchdog;
283import com.android.server.net.NetworkPolicyManagerInternal;
284import com.android.server.pm.Installer.InstallerException;
285import com.android.server.pm.PermissionsState.PermissionState;
286import com.android.server.pm.Settings.DatabaseVersion;
287import com.android.server.pm.Settings.VersionInfo;
288import com.android.server.pm.dex.ArtManagerService;
289import com.android.server.pm.dex.DexLogger;
290import com.android.server.pm.dex.DexManager;
291import com.android.server.pm.dex.DexoptOptions;
292import com.android.server.pm.dex.PackageDexUsage;
293import com.android.server.storage.DeviceStorageMonitorInternal;
294
295import dalvik.system.CloseGuard;
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.LinkedHashSet;
342import java.util.List;
343import java.util.Map;
344import java.util.Objects;
345import java.util.Set;
346import java.util.concurrent.CountDownLatch;
347import java.util.concurrent.Future;
348import java.util.concurrent.TimeUnit;
349import java.util.concurrent.atomic.AtomicBoolean;
350import java.util.concurrent.atomic.AtomicInteger;
351import java.util.zip.GZIPInputStream;
352
353/**
354 * Keep track of all those APKs everywhere.
355 * <p>
356 * Internally there are two important locks:
357 * <ul>
358 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
359 * and other related state. It is a fine-grained lock that should only be held
360 * momentarily, as it's one of the most contended locks in the system.
361 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
362 * operations typically involve heavy lifting of application data on disk. Since
363 * {@code installd} is single-threaded, and it's operations can often be slow,
364 * this lock should never be acquired while already holding {@link #mPackages}.
365 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
366 * holding {@link #mInstallLock}.
367 * </ul>
368 * Many internal methods rely on the caller to hold the appropriate locks, and
369 * this contract is expressed through method name suffixes:
370 * <ul>
371 * <li>fooLI(): the caller must hold {@link #mInstallLock}
372 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
373 * being modified must be frozen
374 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
375 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
376 * </ul>
377 * <p>
378 * Because this class is very central to the platform's security; please run all
379 * CTS and unit tests whenever making modifications:
380 *
381 * <pre>
382 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
383 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
384 * </pre>
385 */
386public class PackageManagerService extends IPackageManager.Stub
387        implements PackageSender {
388    static final String TAG = "PackageManager";
389    static final boolean DEBUG_SETTINGS = false;
390    static final boolean DEBUG_PREFERRED = false;
391    static final boolean DEBUG_UPGRADE = false;
392    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
393    private static final boolean DEBUG_BACKUP = false;
394    private static final boolean DEBUG_INSTALL = false;
395    private static final boolean DEBUG_REMOVE = false;
396    private static final boolean DEBUG_BROADCASTS = false;
397    private static final boolean DEBUG_SHOW_INFO = false;
398    private static final boolean DEBUG_PACKAGE_INFO = false;
399    private static final boolean DEBUG_INTENT_MATCHING = false;
400    private static final boolean DEBUG_PACKAGE_SCANNING = false;
401    private static final boolean DEBUG_VERIFY = false;
402    private static final boolean DEBUG_FILTERS = false;
403    private static final boolean DEBUG_PERMISSIONS = false;
404    private static final boolean DEBUG_SHARED_LIBRARIES = false;
405    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
406
407    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
408    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
409    // user, but by default initialize to this.
410    public static final boolean DEBUG_DEXOPT = false;
411
412    private static final boolean DEBUG_ABI_SELECTION = false;
413    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
414    private static final boolean DEBUG_TRIAGED_MISSING = false;
415    private static final boolean DEBUG_APP_DATA = false;
416
417    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
418    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
419
420    private static final boolean HIDE_EPHEMERAL_APIS = false;
421
422    private static final boolean ENABLE_FREE_CACHE_V2 =
423            SystemProperties.getBoolean("fw.free_cache_v2", true);
424
425    private static final int RADIO_UID = Process.PHONE_UID;
426    private static final int LOG_UID = Process.LOG_UID;
427    private static final int NFC_UID = Process.NFC_UID;
428    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
429    private static final int SHELL_UID = Process.SHELL_UID;
430    private static final int SE_UID = Process.SE_UID;
431
432    // Cap the size of permission trees that 3rd party apps can define
433    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
434
435    // Suffix used during package installation when copying/moving
436    // package apks to install directory.
437    private static final String INSTALL_PACKAGE_SUFFIX = "-";
438
439    static final int SCAN_NO_DEX = 1<<1;
440    static final int SCAN_FORCE_DEX = 1<<2;
441    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
442    static final int SCAN_NEW_INSTALL = 1<<4;
443    static final int SCAN_UPDATE_TIME = 1<<5;
444    static final int SCAN_BOOTING = 1<<6;
445    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
446    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
447    static final int SCAN_REPLACING = 1<<9;
448    static final int SCAN_REQUIRE_KNOWN = 1<<10;
449    static final int SCAN_MOVE = 1<<11;
450    static final int SCAN_INITIAL = 1<<12;
451    static final int SCAN_CHECK_ONLY = 1<<13;
452    static final int SCAN_DONT_KILL_APP = 1<<14;
453    static final int SCAN_IGNORE_FROZEN = 1<<15;
454    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
455    static final int SCAN_AS_INSTANT_APP = 1<<17;
456    static final int SCAN_AS_FULL_APP = 1<<18;
457    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
458    /** Should not be with the scan flags */
459    static final int FLAGS_REMOVE_CHATTY = 1<<31;
460
461    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
462    /** Extension of the compressed packages */
463    private final static String COMPRESSED_EXTENSION = ".gz";
464    /** Suffix of stub packages on the system partition */
465    private final static String STUB_SUFFIX = "-Stub";
466
467    private static final int[] EMPTY_INT_ARRAY = new int[0];
468
469    private static final int TYPE_UNKNOWN = 0;
470    private static final int TYPE_ACTIVITY = 1;
471    private static final int TYPE_RECEIVER = 2;
472    private static final int TYPE_SERVICE = 3;
473    private static final int TYPE_PROVIDER = 4;
474    @IntDef(prefix = { "TYPE_" }, value = {
475            TYPE_UNKNOWN,
476            TYPE_ACTIVITY,
477            TYPE_RECEIVER,
478            TYPE_SERVICE,
479            TYPE_PROVIDER,
480    })
481    @Retention(RetentionPolicy.SOURCE)
482    public @interface ComponentType {}
483
484    /**
485     * Timeout (in milliseconds) after which the watchdog should declare that
486     * our handler thread is wedged.  The usual default for such things is one
487     * minute but we sometimes do very lengthy I/O operations on this thread,
488     * such as installing multi-gigabyte applications, so ours needs to be longer.
489     */
490    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
491
492    /**
493     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
494     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
495     * settings entry if available, otherwise we use the hardcoded default.  If it's been
496     * more than this long since the last fstrim, we force one during the boot sequence.
497     *
498     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
499     * one gets run at the next available charging+idle time.  This final mandatory
500     * no-fstrim check kicks in only of the other scheduling criteria is never met.
501     */
502    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
503
504    /**
505     * Whether verification is enabled by default.
506     */
507    private static final boolean DEFAULT_VERIFY_ENABLE = true;
508
509    /**
510     * The default maximum time to wait for the verification agent to return in
511     * milliseconds.
512     */
513    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
514
515    /**
516     * The default response for package verification timeout.
517     *
518     * This can be either PackageManager.VERIFICATION_ALLOW or
519     * PackageManager.VERIFICATION_REJECT.
520     */
521    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
522
523    static final String PLATFORM_PACKAGE_NAME = "android";
524
525    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
526
527    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
528            DEFAULT_CONTAINER_PACKAGE,
529            "com.android.defcontainer.DefaultContainerService");
530
531    private static final String KILL_APP_REASON_GIDS_CHANGED =
532            "permission grant or revoke changed gids";
533
534    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
535            "permissions revoked";
536
537    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
538
539    private static final String PACKAGE_SCHEME = "package";
540
541    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
542
543    /** Permission grant: not grant the permission. */
544    private static final int GRANT_DENIED = 1;
545
546    /** Permission grant: grant the permission as an install permission. */
547    private static final int GRANT_INSTALL = 2;
548
549    /** Permission grant: grant the permission as a runtime one. */
550    private static final int GRANT_RUNTIME = 3;
551
552    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
553    private static final int GRANT_UPGRADE = 4;
554
555    /** Canonical intent used to identify what counts as a "web browser" app */
556    private static final Intent sBrowserIntent;
557    static {
558        sBrowserIntent = new Intent();
559        sBrowserIntent.setAction(Intent.ACTION_VIEW);
560        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
561        sBrowserIntent.setData(Uri.parse("http:"));
562    }
563
564    /**
565     * The set of all protected actions [i.e. those actions for which a high priority
566     * intent filter is disallowed].
567     */
568    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
569    static {
570        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
571        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
572        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
573        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
574    }
575
576    // Compilation reasons.
577    public static final int REASON_FIRST_BOOT = 0;
578    public static final int REASON_BOOT = 1;
579    public static final int REASON_INSTALL = 2;
580    public static final int REASON_BACKGROUND_DEXOPT = 3;
581    public static final int REASON_AB_OTA = 4;
582    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
583    public static final int REASON_SHARED = 6;
584
585    public static final int REASON_LAST = REASON_SHARED;
586
587    /** All dangerous permission names in the same order as the events in MetricsEvent */
588    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
589            Manifest.permission.READ_CALENDAR,
590            Manifest.permission.WRITE_CALENDAR,
591            Manifest.permission.CAMERA,
592            Manifest.permission.READ_CONTACTS,
593            Manifest.permission.WRITE_CONTACTS,
594            Manifest.permission.GET_ACCOUNTS,
595            Manifest.permission.ACCESS_FINE_LOCATION,
596            Manifest.permission.ACCESS_COARSE_LOCATION,
597            Manifest.permission.RECORD_AUDIO,
598            Manifest.permission.READ_PHONE_STATE,
599            Manifest.permission.CALL_PHONE,
600            Manifest.permission.READ_CALL_LOG,
601            Manifest.permission.WRITE_CALL_LOG,
602            Manifest.permission.ADD_VOICEMAIL,
603            Manifest.permission.USE_SIP,
604            Manifest.permission.PROCESS_OUTGOING_CALLS,
605            Manifest.permission.READ_CELL_BROADCASTS,
606            Manifest.permission.BODY_SENSORS,
607            Manifest.permission.SEND_SMS,
608            Manifest.permission.RECEIVE_SMS,
609            Manifest.permission.READ_SMS,
610            Manifest.permission.RECEIVE_WAP_PUSH,
611            Manifest.permission.RECEIVE_MMS,
612            Manifest.permission.READ_EXTERNAL_STORAGE,
613            Manifest.permission.WRITE_EXTERNAL_STORAGE,
614            Manifest.permission.READ_PHONE_NUMBERS,
615            Manifest.permission.ANSWER_PHONE_CALLS,
616            Manifest.permission.ACCEPT_HANDOVER);
617
618
619    /**
620     * Version number for the package parser cache. Increment this whenever the format or
621     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
622     */
623    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
624
625    /**
626     * Whether the package parser cache is enabled.
627     */
628    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
629
630    final ServiceThread mHandlerThread;
631
632    final PackageHandler mHandler;
633
634    private final ProcessLoggingHandler mProcessLoggingHandler;
635
636    /**
637     * Messages for {@link #mHandler} that need to wait for system ready before
638     * being dispatched.
639     */
640    private ArrayList<Message> mPostSystemReadyMessages;
641
642    final int mSdkVersion = Build.VERSION.SDK_INT;
643
644    final Context mContext;
645    final boolean mFactoryTest;
646    final boolean mOnlyCore;
647    final DisplayMetrics mMetrics;
648    final int mDefParseFlags;
649    final String[] mSeparateProcesses;
650    final boolean mIsUpgrade;
651    final boolean mIsPreNUpgrade;
652    final boolean mIsPreNMR1Upgrade;
653
654    // Have we told the Activity Manager to whitelist the default container service by uid yet?
655    @GuardedBy("mPackages")
656    boolean mDefaultContainerWhitelisted = false;
657
658    @GuardedBy("mPackages")
659    private boolean mDexOptDialogShown;
660
661    /** The location for ASEC container files on internal storage. */
662    final String mAsecInternalPath;
663
664    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
665    // LOCK HELD.  Can be called with mInstallLock held.
666    @GuardedBy("mInstallLock")
667    final Installer mInstaller;
668
669    /** Directory where installed third-party apps stored */
670    final File mAppInstallDir;
671
672    /**
673     * Directory to which applications installed internally have their
674     * 32 bit native libraries copied.
675     */
676    private File mAppLib32InstallDir;
677
678    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
679    // apps.
680    final File mDrmAppPrivateInstallDir;
681
682    // ----------------------------------------------------------------
683
684    // Lock for state used when installing and doing other long running
685    // operations.  Methods that must be called with this lock held have
686    // the suffix "LI".
687    final Object mInstallLock = new Object();
688
689    // ----------------------------------------------------------------
690
691    // Keys are String (package name), values are Package.  This also serves
692    // as the lock for the global state.  Methods that must be called with
693    // this lock held have the prefix "LP".
694    @GuardedBy("mPackages")
695    final ArrayMap<String, PackageParser.Package> mPackages =
696            new ArrayMap<String, PackageParser.Package>();
697
698    final ArrayMap<String, Set<String>> mKnownCodebase =
699            new ArrayMap<String, Set<String>>();
700
701    // Keys are isolated uids and values are the uid of the application
702    // that created the isolated proccess.
703    @GuardedBy("mPackages")
704    final SparseIntArray mIsolatedOwners = new SparseIntArray();
705
706    /**
707     * Tracks new system packages [received in an OTA] that we expect to
708     * find updated user-installed versions. Keys are package name, values
709     * are package location.
710     */
711    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
712    /**
713     * Tracks high priority intent filters for protected actions. During boot, certain
714     * filter actions are protected and should never be allowed to have a high priority
715     * intent filter for them. However, there is one, and only one exception -- the
716     * setup wizard. It must be able to define a high priority intent filter for these
717     * actions to ensure there are no escapes from the wizard. We need to delay processing
718     * of these during boot as we need to look at all of the system packages in order
719     * to know which component is the setup wizard.
720     */
721    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
722    /**
723     * Whether or not processing protected filters should be deferred.
724     */
725    private boolean mDeferProtectedFilters = true;
726
727    /**
728     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
729     */
730    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
731    /**
732     * Whether or not system app permissions should be promoted from install to runtime.
733     */
734    boolean mPromoteSystemApps;
735
736    @GuardedBy("mPackages")
737    final Settings mSettings;
738
739    /**
740     * Set of package names that are currently "frozen", which means active
741     * surgery is being done on the code/data for that package. The platform
742     * will refuse to launch frozen packages to avoid race conditions.
743     *
744     * @see PackageFreezer
745     */
746    @GuardedBy("mPackages")
747    final ArraySet<String> mFrozenPackages = new ArraySet<>();
748
749    final ProtectedPackages mProtectedPackages;
750
751    @GuardedBy("mLoadedVolumes")
752    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
753
754    boolean mFirstBoot;
755
756    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
757
758    // System configuration read by SystemConfig.
759    final int[] mGlobalGids;
760    final SparseArray<ArraySet<String>> mSystemPermissions;
761    @GuardedBy("mAvailableFeatures")
762    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
763
764    // If mac_permissions.xml was found for seinfo labeling.
765    boolean mFoundPolicyFile;
766
767    private final InstantAppRegistry mInstantAppRegistry;
768
769    @GuardedBy("mPackages")
770    int mChangedPackagesSequenceNumber;
771    /**
772     * List of changed [installed, removed or updated] packages.
773     * mapping from user id -> sequence number -> package name
774     */
775    @GuardedBy("mPackages")
776    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
777    /**
778     * The sequence number of the last change to a package.
779     * mapping from user id -> package name -> sequence number
780     */
781    @GuardedBy("mPackages")
782    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
783
784    class PackageParserCallback implements PackageParser.Callback {
785        @Override public final boolean hasFeature(String feature) {
786            return PackageManagerService.this.hasSystemFeature(feature, 0);
787        }
788
789        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
790                Collection<PackageParser.Package> allPackages, String targetPackageName) {
791            List<PackageParser.Package> overlayPackages = null;
792            for (PackageParser.Package p : allPackages) {
793                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
794                    if (overlayPackages == null) {
795                        overlayPackages = new ArrayList<PackageParser.Package>();
796                    }
797                    overlayPackages.add(p);
798                }
799            }
800            if (overlayPackages != null) {
801                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
802                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
803                        return p1.mOverlayPriority - p2.mOverlayPriority;
804                    }
805                };
806                Collections.sort(overlayPackages, cmp);
807            }
808            return overlayPackages;
809        }
810
811        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
812                String targetPackageName, String targetPath) {
813            if ("android".equals(targetPackageName)) {
814                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
815                // native AssetManager.
816                return null;
817            }
818            List<PackageParser.Package> overlayPackages =
819                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
820            if (overlayPackages == null || overlayPackages.isEmpty()) {
821                return null;
822            }
823            List<String> overlayPathList = null;
824            for (PackageParser.Package overlayPackage : overlayPackages) {
825                if (targetPath == null) {
826                    if (overlayPathList == null) {
827                        overlayPathList = new ArrayList<String>();
828                    }
829                    overlayPathList.add(overlayPackage.baseCodePath);
830                    continue;
831                }
832
833                try {
834                    // Creates idmaps for system to parse correctly the Android manifest of the
835                    // target package.
836                    //
837                    // OverlayManagerService will update each of them with a correct gid from its
838                    // target package app id.
839                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
840                            UserHandle.getSharedAppGid(
841                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
842                    if (overlayPathList == null) {
843                        overlayPathList = new ArrayList<String>();
844                    }
845                    overlayPathList.add(overlayPackage.baseCodePath);
846                } catch (InstallerException e) {
847                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
848                            overlayPackage.baseCodePath);
849                }
850            }
851            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
852        }
853
854        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
855            synchronized (mPackages) {
856                return getStaticOverlayPathsLocked(
857                        mPackages.values(), targetPackageName, targetPath);
858            }
859        }
860
861        @Override public final String[] getOverlayApks(String targetPackageName) {
862            return getStaticOverlayPaths(targetPackageName, null);
863        }
864
865        @Override public final String[] getOverlayPaths(String targetPackageName,
866                String targetPath) {
867            return getStaticOverlayPaths(targetPackageName, targetPath);
868        }
869    };
870
871    class ParallelPackageParserCallback extends PackageParserCallback {
872        List<PackageParser.Package> mOverlayPackages = null;
873
874        void findStaticOverlayPackages() {
875            synchronized (mPackages) {
876                for (PackageParser.Package p : mPackages.values()) {
877                    if (p.mIsStaticOverlay) {
878                        if (mOverlayPackages == null) {
879                            mOverlayPackages = new ArrayList<PackageParser.Package>();
880                        }
881                        mOverlayPackages.add(p);
882                    }
883                }
884            }
885        }
886
887        @Override
888        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
889            // We can trust mOverlayPackages without holding mPackages because package uninstall
890            // can't happen while running parallel parsing.
891            // Moreover holding mPackages on each parsing thread causes dead-lock.
892            return mOverlayPackages == null ? null :
893                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
894        }
895    }
896
897    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
898    final ParallelPackageParserCallback mParallelPackageParserCallback =
899            new ParallelPackageParserCallback();
900
901    public static final class SharedLibraryEntry {
902        public final @Nullable String path;
903        public final @Nullable String apk;
904        public final @NonNull SharedLibraryInfo info;
905
906        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
907                String declaringPackageName, int declaringPackageVersionCode) {
908            path = _path;
909            apk = _apk;
910            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
911                    declaringPackageName, declaringPackageVersionCode), null);
912        }
913    }
914
915    // Currently known shared libraries.
916    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
917    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
918            new ArrayMap<>();
919
920    // All available activities, for your resolving pleasure.
921    final ActivityIntentResolver mActivities =
922            new ActivityIntentResolver();
923
924    // All available receivers, for your resolving pleasure.
925    final ActivityIntentResolver mReceivers =
926            new ActivityIntentResolver();
927
928    // All available services, for your resolving pleasure.
929    final ServiceIntentResolver mServices = new ServiceIntentResolver();
930
931    // All available providers, for your resolving pleasure.
932    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
933
934    // Mapping from provider base names (first directory in content URI codePath)
935    // to the provider information.
936    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
937            new ArrayMap<String, PackageParser.Provider>();
938
939    // Mapping from instrumentation class names to info about them.
940    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
941            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
942
943    // Mapping from permission names to info about them.
944    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
945            new ArrayMap<String, PackageParser.PermissionGroup>();
946
947    // Packages whose data we have transfered into another package, thus
948    // should no longer exist.
949    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
950
951    // Broadcast actions that are only available to the system.
952    @GuardedBy("mProtectedBroadcasts")
953    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
954
955    /** List of packages waiting for verification. */
956    final SparseArray<PackageVerificationState> mPendingVerification
957            = new SparseArray<PackageVerificationState>();
958
959    /** Set of packages associated with each app op permission. */
960    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
961
962    final PackageInstallerService mInstallerService;
963
964    final ArtManagerService mArtManagerService;
965
966    private final PackageDexOptimizer mPackageDexOptimizer;
967    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
968    // is used by other apps).
969    private final DexManager mDexManager;
970
971    private AtomicInteger mNextMoveId = new AtomicInteger();
972    private final MoveCallbacks mMoveCallbacks;
973
974    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
975
976    // Cache of users who need badging.
977    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
978
979    /** Token for keys in mPendingVerification. */
980    private int mPendingVerificationToken = 0;
981
982    volatile boolean mSystemReady;
983    volatile boolean mSafeMode;
984    volatile boolean mHasSystemUidErrors;
985    private volatile boolean mEphemeralAppsDisabled;
986
987    ApplicationInfo mAndroidApplication;
988    final ActivityInfo mResolveActivity = new ActivityInfo();
989    final ResolveInfo mResolveInfo = new ResolveInfo();
990    ComponentName mResolveComponentName;
991    PackageParser.Package mPlatformPackage;
992    ComponentName mCustomResolverComponentName;
993
994    boolean mResolverReplaced = false;
995
996    private final @Nullable ComponentName mIntentFilterVerifierComponent;
997    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
998
999    private int mIntentFilterVerificationToken = 0;
1000
1001    /** The service connection to the ephemeral resolver */
1002    final EphemeralResolverConnection mInstantAppResolverConnection;
1003    /** Component used to show resolver settings for Instant Apps */
1004    final ComponentName mInstantAppResolverSettingsComponent;
1005
1006    /** Activity used to install instant applications */
1007    ActivityInfo mInstantAppInstallerActivity;
1008    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1009
1010    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1011            = new SparseArray<IntentFilterVerificationState>();
1012
1013    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1014
1015    // List of packages names to keep cached, even if they are uninstalled for all users
1016    private List<String> mKeepUninstalledPackages;
1017
1018    private UserManagerInternal mUserManagerInternal;
1019
1020    private DeviceIdleController.LocalService mDeviceIdleController;
1021
1022    private File mCacheDir;
1023
1024    private ArraySet<String> mPrivappPermissionsViolations;
1025
1026    private Future<?> mPrepareAppDataFuture;
1027
1028    private static class IFVerificationParams {
1029        PackageParser.Package pkg;
1030        boolean replacing;
1031        int userId;
1032        int verifierUid;
1033
1034        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1035                int _userId, int _verifierUid) {
1036            pkg = _pkg;
1037            replacing = _replacing;
1038            userId = _userId;
1039            replacing = _replacing;
1040            verifierUid = _verifierUid;
1041        }
1042    }
1043
1044    private interface IntentFilterVerifier<T extends IntentFilter> {
1045        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1046                                               T filter, String packageName);
1047        void startVerifications(int userId);
1048        void receiveVerificationResponse(int verificationId);
1049    }
1050
1051    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1052        private Context mContext;
1053        private ComponentName mIntentFilterVerifierComponent;
1054        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1055
1056        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1057            mContext = context;
1058            mIntentFilterVerifierComponent = verifierComponent;
1059        }
1060
1061        private String getDefaultScheme() {
1062            return IntentFilter.SCHEME_HTTPS;
1063        }
1064
1065        @Override
1066        public void startVerifications(int userId) {
1067            // Launch verifications requests
1068            int count = mCurrentIntentFilterVerifications.size();
1069            for (int n=0; n<count; n++) {
1070                int verificationId = mCurrentIntentFilterVerifications.get(n);
1071                final IntentFilterVerificationState ivs =
1072                        mIntentFilterVerificationStates.get(verificationId);
1073
1074                String packageName = ivs.getPackageName();
1075
1076                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1077                final int filterCount = filters.size();
1078                ArraySet<String> domainsSet = new ArraySet<>();
1079                for (int m=0; m<filterCount; m++) {
1080                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1081                    domainsSet.addAll(filter.getHostsList());
1082                }
1083                synchronized (mPackages) {
1084                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1085                            packageName, domainsSet) != null) {
1086                        scheduleWriteSettingsLocked();
1087                    }
1088                }
1089                sendVerificationRequest(verificationId, ivs);
1090            }
1091            mCurrentIntentFilterVerifications.clear();
1092        }
1093
1094        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1095            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1098                    verificationId);
1099            verificationIntent.putExtra(
1100                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1101                    getDefaultScheme());
1102            verificationIntent.putExtra(
1103                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1104                    ivs.getHostsString());
1105            verificationIntent.putExtra(
1106                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1107                    ivs.getPackageName());
1108            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1109            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1110
1111            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1112            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1113                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1114                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1115
1116            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1117            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1118                    "Sending IntentFilter verification broadcast");
1119        }
1120
1121        public void receiveVerificationResponse(int verificationId) {
1122            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1123
1124            final boolean verified = ivs.isVerified();
1125
1126            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1127            final int count = filters.size();
1128            if (DEBUG_DOMAIN_VERIFICATION) {
1129                Slog.i(TAG, "Received verification response " + verificationId
1130                        + " for " + count + " filters, verified=" + verified);
1131            }
1132            for (int n=0; n<count; n++) {
1133                PackageParser.ActivityIntentInfo filter = filters.get(n);
1134                filter.setVerified(verified);
1135
1136                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1137                        + " verified with result:" + verified + " and hosts:"
1138                        + ivs.getHostsString());
1139            }
1140
1141            mIntentFilterVerificationStates.remove(verificationId);
1142
1143            final String packageName = ivs.getPackageName();
1144            IntentFilterVerificationInfo ivi = null;
1145
1146            synchronized (mPackages) {
1147                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1148            }
1149            if (ivi == null) {
1150                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1151                        + verificationId + " packageName:" + packageName);
1152                return;
1153            }
1154            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1155                    "Updating IntentFilterVerificationInfo for package " + packageName
1156                            +" verificationId:" + verificationId);
1157
1158            synchronized (mPackages) {
1159                if (verified) {
1160                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1161                } else {
1162                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1163                }
1164                scheduleWriteSettingsLocked();
1165
1166                final int userId = ivs.getUserId();
1167                if (userId != UserHandle.USER_ALL) {
1168                    final int userStatus =
1169                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1170
1171                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1172                    boolean needUpdate = false;
1173
1174                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1175                    // already been set by the User thru the Disambiguation dialog
1176                    switch (userStatus) {
1177                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1178                            if (verified) {
1179                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1180                            } else {
1181                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1182                            }
1183                            needUpdate = true;
1184                            break;
1185
1186                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1187                            if (verified) {
1188                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1189                                needUpdate = true;
1190                            }
1191                            break;
1192
1193                        default:
1194                            // Nothing to do
1195                    }
1196
1197                    if (needUpdate) {
1198                        mSettings.updateIntentFilterVerificationStatusLPw(
1199                                packageName, updatedStatus, userId);
1200                        scheduleWritePackageRestrictionsLocked(userId);
1201                    }
1202                }
1203            }
1204        }
1205
1206        @Override
1207        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1208                    ActivityIntentInfo filter, String packageName) {
1209            if (!hasValidDomains(filter)) {
1210                return false;
1211            }
1212            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1213            if (ivs == null) {
1214                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1215                        packageName);
1216            }
1217            if (DEBUG_DOMAIN_VERIFICATION) {
1218                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1219            }
1220            ivs.addFilter(filter);
1221            return true;
1222        }
1223
1224        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1225                int userId, int verificationId, String packageName) {
1226            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1227                    verifierUid, userId, packageName);
1228            ivs.setPendingState();
1229            synchronized (mPackages) {
1230                mIntentFilterVerificationStates.append(verificationId, ivs);
1231                mCurrentIntentFilterVerifications.add(verificationId);
1232            }
1233            return ivs;
1234        }
1235    }
1236
1237    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1238        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1239                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1240                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1241    }
1242
1243    // Set of pending broadcasts for aggregating enable/disable of components.
1244    static class PendingPackageBroadcasts {
1245        // for each user id, a map of <package name -> components within that package>
1246        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1247
1248        public PendingPackageBroadcasts() {
1249            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1250        }
1251
1252        public ArrayList<String> get(int userId, String packageName) {
1253            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1254            return packages.get(packageName);
1255        }
1256
1257        public void put(int userId, String packageName, ArrayList<String> components) {
1258            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1259            packages.put(packageName, components);
1260        }
1261
1262        public void remove(int userId, String packageName) {
1263            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1264            if (packages != null) {
1265                packages.remove(packageName);
1266            }
1267        }
1268
1269        public void remove(int userId) {
1270            mUidMap.remove(userId);
1271        }
1272
1273        public int userIdCount() {
1274            return mUidMap.size();
1275        }
1276
1277        public int userIdAt(int n) {
1278            return mUidMap.keyAt(n);
1279        }
1280
1281        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1282            return mUidMap.get(userId);
1283        }
1284
1285        public int size() {
1286            // total number of pending broadcast entries across all userIds
1287            int num = 0;
1288            for (int i = 0; i< mUidMap.size(); i++) {
1289                num += mUidMap.valueAt(i).size();
1290            }
1291            return num;
1292        }
1293
1294        public void clear() {
1295            mUidMap.clear();
1296        }
1297
1298        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1299            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1300            if (map == null) {
1301                map = new ArrayMap<String, ArrayList<String>>();
1302                mUidMap.put(userId, map);
1303            }
1304            return map;
1305        }
1306    }
1307    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1308
1309    // Service Connection to remote media container service to copy
1310    // package uri's from external media onto secure containers
1311    // or internal storage.
1312    private IMediaContainerService mContainerService = null;
1313
1314    static final int SEND_PENDING_BROADCAST = 1;
1315    static final int MCS_BOUND = 3;
1316    static final int END_COPY = 4;
1317    static final int INIT_COPY = 5;
1318    static final int MCS_UNBIND = 6;
1319    static final int START_CLEANING_PACKAGE = 7;
1320    static final int FIND_INSTALL_LOC = 8;
1321    static final int POST_INSTALL = 9;
1322    static final int MCS_RECONNECT = 10;
1323    static final int MCS_GIVE_UP = 11;
1324    static final int UPDATED_MEDIA_STATUS = 12;
1325    static final int WRITE_SETTINGS = 13;
1326    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1327    static final int PACKAGE_VERIFIED = 15;
1328    static final int CHECK_PENDING_VERIFICATION = 16;
1329    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1330    static final int INTENT_FILTER_VERIFIED = 18;
1331    static final int WRITE_PACKAGE_LIST = 19;
1332    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1333
1334    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1335
1336    // Delay time in millisecs
1337    static final int BROADCAST_DELAY = 10 * 1000;
1338
1339    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1340            2 * 60 * 60 * 1000L; /* two hours */
1341
1342    static UserManagerService sUserManager;
1343
1344    // Stores a list of users whose package restrictions file needs to be updated
1345    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1346
1347    final private DefaultContainerConnection mDefContainerConn =
1348            new DefaultContainerConnection();
1349    class DefaultContainerConnection implements ServiceConnection {
1350        public void onServiceConnected(ComponentName name, IBinder service) {
1351            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1352            final IMediaContainerService imcs = IMediaContainerService.Stub
1353                    .asInterface(Binder.allowBlocking(service));
1354            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1355        }
1356
1357        public void onServiceDisconnected(ComponentName name) {
1358            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1359        }
1360    }
1361
1362    // Recordkeeping of restore-after-install operations that are currently in flight
1363    // between the Package Manager and the Backup Manager
1364    static class PostInstallData {
1365        public InstallArgs args;
1366        public PackageInstalledInfo res;
1367
1368        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1369            args = _a;
1370            res = _r;
1371        }
1372    }
1373
1374    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1375    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1376
1377    // XML tags for backup/restore of various bits of state
1378    private static final String TAG_PREFERRED_BACKUP = "pa";
1379    private static final String TAG_DEFAULT_APPS = "da";
1380    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1381
1382    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1383    private static final String TAG_ALL_GRANTS = "rt-grants";
1384    private static final String TAG_GRANT = "grant";
1385    private static final String ATTR_PACKAGE_NAME = "pkg";
1386
1387    private static final String TAG_PERMISSION = "perm";
1388    private static final String ATTR_PERMISSION_NAME = "name";
1389    private static final String ATTR_IS_GRANTED = "g";
1390    private static final String ATTR_USER_SET = "set";
1391    private static final String ATTR_USER_FIXED = "fixed";
1392    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1393
1394    // System/policy permission grants are not backed up
1395    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1396            FLAG_PERMISSION_POLICY_FIXED
1397            | FLAG_PERMISSION_SYSTEM_FIXED
1398            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1399
1400    // And we back up these user-adjusted states
1401    private static final int USER_RUNTIME_GRANT_MASK =
1402            FLAG_PERMISSION_USER_SET
1403            | FLAG_PERMISSION_USER_FIXED
1404            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1405
1406    final @Nullable String mRequiredVerifierPackage;
1407    final @NonNull String mRequiredInstallerPackage;
1408    final @NonNull String mRequiredUninstallerPackage;
1409    final @Nullable String mSetupWizardPackage;
1410    final @Nullable String mStorageManagerPackage;
1411    final @NonNull String mServicesSystemSharedLibraryPackageName;
1412    final @NonNull String mSharedSystemSharedLibraryPackageName;
1413
1414    final boolean mPermissionReviewRequired;
1415
1416    private final PackageUsage mPackageUsage = new PackageUsage();
1417    private final CompilerStats mCompilerStats = new CompilerStats();
1418
1419    class PackageHandler extends Handler {
1420        private boolean mBound = false;
1421        final ArrayList<HandlerParams> mPendingInstalls =
1422            new ArrayList<HandlerParams>();
1423
1424        private boolean connectToService() {
1425            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1426                    " DefaultContainerService");
1427            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1428            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1429            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1430                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1431                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1432                mBound = true;
1433                return true;
1434            }
1435            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1436            return false;
1437        }
1438
1439        private void disconnectService() {
1440            mContainerService = null;
1441            mBound = false;
1442            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1443            mContext.unbindService(mDefContainerConn);
1444            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1445        }
1446
1447        PackageHandler(Looper looper) {
1448            super(looper);
1449        }
1450
1451        public void handleMessage(Message msg) {
1452            try {
1453                doHandleMessage(msg);
1454            } finally {
1455                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1456            }
1457        }
1458
1459        void doHandleMessage(Message msg) {
1460            switch (msg.what) {
1461                case INIT_COPY: {
1462                    HandlerParams params = (HandlerParams) msg.obj;
1463                    int idx = mPendingInstalls.size();
1464                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1465                    // If a bind was already initiated we dont really
1466                    // need to do anything. The pending install
1467                    // will be processed later on.
1468                    if (!mBound) {
1469                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1470                                System.identityHashCode(mHandler));
1471                        // If this is the only one pending we might
1472                        // have to bind to the service again.
1473                        if (!connectToService()) {
1474                            Slog.e(TAG, "Failed to bind to media container service");
1475                            params.serviceError();
1476                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1477                                    System.identityHashCode(mHandler));
1478                            if (params.traceMethod != null) {
1479                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1480                                        params.traceCookie);
1481                            }
1482                            return;
1483                        } else {
1484                            // Once we bind to the service, the first
1485                            // pending request will be processed.
1486                            mPendingInstalls.add(idx, params);
1487                        }
1488                    } else {
1489                        mPendingInstalls.add(idx, params);
1490                        // Already bound to the service. Just make
1491                        // sure we trigger off processing the first request.
1492                        if (idx == 0) {
1493                            mHandler.sendEmptyMessage(MCS_BOUND);
1494                        }
1495                    }
1496                    break;
1497                }
1498                case MCS_BOUND: {
1499                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1500                    if (msg.obj != null) {
1501                        mContainerService = (IMediaContainerService) msg.obj;
1502                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1503                                System.identityHashCode(mHandler));
1504                    }
1505                    if (mContainerService == null) {
1506                        if (!mBound) {
1507                            // Something seriously wrong since we are not bound and we are not
1508                            // waiting for connection. Bail out.
1509                            Slog.e(TAG, "Cannot bind to media container service");
1510                            for (HandlerParams params : mPendingInstalls) {
1511                                // Indicate service bind error
1512                                params.serviceError();
1513                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1514                                        System.identityHashCode(params));
1515                                if (params.traceMethod != null) {
1516                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1517                                            params.traceMethod, params.traceCookie);
1518                                }
1519                                return;
1520                            }
1521                            mPendingInstalls.clear();
1522                        } else {
1523                            Slog.w(TAG, "Waiting to connect to media container service");
1524                        }
1525                    } else if (mPendingInstalls.size() > 0) {
1526                        HandlerParams params = mPendingInstalls.get(0);
1527                        if (params != null) {
1528                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1529                                    System.identityHashCode(params));
1530                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1531                            if (params.startCopy()) {
1532                                // We are done...  look for more work or to
1533                                // go idle.
1534                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1535                                        "Checking for more work or unbind...");
1536                                // Delete pending install
1537                                if (mPendingInstalls.size() > 0) {
1538                                    mPendingInstalls.remove(0);
1539                                }
1540                                if (mPendingInstalls.size() == 0) {
1541                                    if (mBound) {
1542                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1543                                                "Posting delayed MCS_UNBIND");
1544                                        removeMessages(MCS_UNBIND);
1545                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1546                                        // Unbind after a little delay, to avoid
1547                                        // continual thrashing.
1548                                        sendMessageDelayed(ubmsg, 10000);
1549                                    }
1550                                } else {
1551                                    // There are more pending requests in queue.
1552                                    // Just post MCS_BOUND message to trigger processing
1553                                    // of next pending install.
1554                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1555                                            "Posting MCS_BOUND for next work");
1556                                    mHandler.sendEmptyMessage(MCS_BOUND);
1557                                }
1558                            }
1559                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1560                        }
1561                    } else {
1562                        // Should never happen ideally.
1563                        Slog.w(TAG, "Empty queue");
1564                    }
1565                    break;
1566                }
1567                case MCS_RECONNECT: {
1568                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1569                    if (mPendingInstalls.size() > 0) {
1570                        if (mBound) {
1571                            disconnectService();
1572                        }
1573                        if (!connectToService()) {
1574                            Slog.e(TAG, "Failed to bind to media container service");
1575                            for (HandlerParams params : mPendingInstalls) {
1576                                // Indicate service bind error
1577                                params.serviceError();
1578                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1579                                        System.identityHashCode(params));
1580                            }
1581                            mPendingInstalls.clear();
1582                        }
1583                    }
1584                    break;
1585                }
1586                case MCS_UNBIND: {
1587                    // If there is no actual work left, then time to unbind.
1588                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1589
1590                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1591                        if (mBound) {
1592                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1593
1594                            disconnectService();
1595                        }
1596                    } else if (mPendingInstalls.size() > 0) {
1597                        // There are more pending requests in queue.
1598                        // Just post MCS_BOUND message to trigger processing
1599                        // of next pending install.
1600                        mHandler.sendEmptyMessage(MCS_BOUND);
1601                    }
1602
1603                    break;
1604                }
1605                case MCS_GIVE_UP: {
1606                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1607                    HandlerParams params = mPendingInstalls.remove(0);
1608                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1609                            System.identityHashCode(params));
1610                    break;
1611                }
1612                case SEND_PENDING_BROADCAST: {
1613                    String packages[];
1614                    ArrayList<String> components[];
1615                    int size = 0;
1616                    int uids[];
1617                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1618                    synchronized (mPackages) {
1619                        if (mPendingBroadcasts == null) {
1620                            return;
1621                        }
1622                        size = mPendingBroadcasts.size();
1623                        if (size <= 0) {
1624                            // Nothing to be done. Just return
1625                            return;
1626                        }
1627                        packages = new String[size];
1628                        components = new ArrayList[size];
1629                        uids = new int[size];
1630                        int i = 0;  // filling out the above arrays
1631
1632                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1633                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1634                            Iterator<Map.Entry<String, ArrayList<String>>> it
1635                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1636                                            .entrySet().iterator();
1637                            while (it.hasNext() && i < size) {
1638                                Map.Entry<String, ArrayList<String>> ent = it.next();
1639                                packages[i] = ent.getKey();
1640                                components[i] = ent.getValue();
1641                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1642                                uids[i] = (ps != null)
1643                                        ? UserHandle.getUid(packageUserId, ps.appId)
1644                                        : -1;
1645                                i++;
1646                            }
1647                        }
1648                        size = i;
1649                        mPendingBroadcasts.clear();
1650                    }
1651                    // Send broadcasts
1652                    for (int i = 0; i < size; i++) {
1653                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1654                    }
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1656                    break;
1657                }
1658                case START_CLEANING_PACKAGE: {
1659                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1660                    final String packageName = (String)msg.obj;
1661                    final int userId = msg.arg1;
1662                    final boolean andCode = msg.arg2 != 0;
1663                    synchronized (mPackages) {
1664                        if (userId == UserHandle.USER_ALL) {
1665                            int[] users = sUserManager.getUserIds();
1666                            for (int user : users) {
1667                                mSettings.addPackageToCleanLPw(
1668                                        new PackageCleanItem(user, packageName, andCode));
1669                            }
1670                        } else {
1671                            mSettings.addPackageToCleanLPw(
1672                                    new PackageCleanItem(userId, packageName, andCode));
1673                        }
1674                    }
1675                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1676                    startCleaningPackages();
1677                } break;
1678                case POST_INSTALL: {
1679                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1680
1681                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1682                    final boolean didRestore = (msg.arg2 != 0);
1683                    mRunningInstalls.delete(msg.arg1);
1684
1685                    if (data != null) {
1686                        InstallArgs args = data.args;
1687                        PackageInstalledInfo parentRes = data.res;
1688
1689                        final boolean grantPermissions = (args.installFlags
1690                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1691                        final boolean killApp = (args.installFlags
1692                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1693                        final boolean virtualPreload = ((args.installFlags
1694                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1695                        final String[] grantedPermissions = args.installGrantPermissions;
1696
1697                        // Handle the parent package
1698                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1699                                virtualPreload, grantedPermissions, didRestore,
1700                                args.installerPackageName, args.observer);
1701
1702                        // Handle the child packages
1703                        final int childCount = (parentRes.addedChildPackages != null)
1704                                ? parentRes.addedChildPackages.size() : 0;
1705                        for (int i = 0; i < childCount; i++) {
1706                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1707                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1708                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1709                                    args.installerPackageName, args.observer);
1710                        }
1711
1712                        // Log tracing if needed
1713                        if (args.traceMethod != null) {
1714                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1715                                    args.traceCookie);
1716                        }
1717                    } else {
1718                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1719                    }
1720
1721                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1722                } break;
1723                case UPDATED_MEDIA_STATUS: {
1724                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1725                    boolean reportStatus = msg.arg1 == 1;
1726                    boolean doGc = msg.arg2 == 1;
1727                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1728                    if (doGc) {
1729                        // Force a gc to clear up stale containers.
1730                        Runtime.getRuntime().gc();
1731                    }
1732                    if (msg.obj != null) {
1733                        @SuppressWarnings("unchecked")
1734                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1735                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1736                        // Unload containers
1737                        unloadAllContainers(args);
1738                    }
1739                    if (reportStatus) {
1740                        try {
1741                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1742                                    "Invoking StorageManagerService call back");
1743                            PackageHelper.getStorageManager().finishMediaUpdate();
1744                        } catch (RemoteException e) {
1745                            Log.e(TAG, "StorageManagerService not running?");
1746                        }
1747                    }
1748                } break;
1749                case WRITE_SETTINGS: {
1750                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1751                    synchronized (mPackages) {
1752                        removeMessages(WRITE_SETTINGS);
1753                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1754                        mSettings.writeLPr();
1755                        mDirtyUsers.clear();
1756                    }
1757                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1758                } break;
1759                case WRITE_PACKAGE_RESTRICTIONS: {
1760                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1761                    synchronized (mPackages) {
1762                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1763                        for (int userId : mDirtyUsers) {
1764                            mSettings.writePackageRestrictionsLPr(userId);
1765                        }
1766                        mDirtyUsers.clear();
1767                    }
1768                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1769                } break;
1770                case WRITE_PACKAGE_LIST: {
1771                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1772                    synchronized (mPackages) {
1773                        removeMessages(WRITE_PACKAGE_LIST);
1774                        mSettings.writePackageListLPr(msg.arg1);
1775                    }
1776                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1777                } break;
1778                case CHECK_PENDING_VERIFICATION: {
1779                    final int verificationId = msg.arg1;
1780                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1781
1782                    if ((state != null) && !state.timeoutExtended()) {
1783                        final InstallArgs args = state.getInstallArgs();
1784                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1785
1786                        Slog.i(TAG, "Verification timed out for " + originUri);
1787                        mPendingVerification.remove(verificationId);
1788
1789                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1790
1791                        final UserHandle user = args.getUser();
1792                        if (getDefaultVerificationResponse(user)
1793                                == PackageManager.VERIFICATION_ALLOW) {
1794                            Slog.i(TAG, "Continuing with installation of " + originUri);
1795                            state.setVerifierResponse(Binder.getCallingUid(),
1796                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1797                            broadcastPackageVerified(verificationId, originUri,
1798                                    PackageManager.VERIFICATION_ALLOW, user);
1799                            try {
1800                                ret = args.copyApk(mContainerService, true);
1801                            } catch (RemoteException e) {
1802                                Slog.e(TAG, "Could not contact the ContainerService");
1803                            }
1804                        } else {
1805                            broadcastPackageVerified(verificationId, originUri,
1806                                    PackageManager.VERIFICATION_REJECT, user);
1807                        }
1808
1809                        Trace.asyncTraceEnd(
1810                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1811
1812                        processPendingInstall(args, ret);
1813                        mHandler.sendEmptyMessage(MCS_UNBIND);
1814                    }
1815                    break;
1816                }
1817                case PACKAGE_VERIFIED: {
1818                    final int verificationId = msg.arg1;
1819
1820                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1821                    if (state == null) {
1822                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1823                        break;
1824                    }
1825
1826                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1827
1828                    state.setVerifierResponse(response.callerUid, response.code);
1829
1830                    if (state.isVerificationComplete()) {
1831                        mPendingVerification.remove(verificationId);
1832
1833                        final InstallArgs args = state.getInstallArgs();
1834                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1835
1836                        int ret;
1837                        if (state.isInstallAllowed()) {
1838                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1839                            broadcastPackageVerified(verificationId, originUri,
1840                                    response.code, state.getInstallArgs().getUser());
1841                            try {
1842                                ret = args.copyApk(mContainerService, true);
1843                            } catch (RemoteException e) {
1844                                Slog.e(TAG, "Could not contact the ContainerService");
1845                            }
1846                        } else {
1847                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1848                        }
1849
1850                        Trace.asyncTraceEnd(
1851                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1852
1853                        processPendingInstall(args, ret);
1854                        mHandler.sendEmptyMessage(MCS_UNBIND);
1855                    }
1856
1857                    break;
1858                }
1859                case START_INTENT_FILTER_VERIFICATIONS: {
1860                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1861                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1862                            params.replacing, params.pkg);
1863                    break;
1864                }
1865                case INTENT_FILTER_VERIFIED: {
1866                    final int verificationId = msg.arg1;
1867
1868                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1869                            verificationId);
1870                    if (state == null) {
1871                        Slog.w(TAG, "Invalid IntentFilter verification token "
1872                                + verificationId + " received");
1873                        break;
1874                    }
1875
1876                    final int userId = state.getUserId();
1877
1878                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1879                            "Processing IntentFilter verification with token:"
1880                            + verificationId + " and userId:" + userId);
1881
1882                    final IntentFilterVerificationResponse response =
1883                            (IntentFilterVerificationResponse) msg.obj;
1884
1885                    state.setVerifierResponse(response.callerUid, response.code);
1886
1887                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1888                            "IntentFilter verification with token:" + verificationId
1889                            + " and userId:" + userId
1890                            + " is settings verifier response with response code:"
1891                            + response.code);
1892
1893                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1894                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1895                                + response.getFailedDomainsString());
1896                    }
1897
1898                    if (state.isVerificationComplete()) {
1899                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1900                    } else {
1901                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1902                                "IntentFilter verification with token:" + verificationId
1903                                + " was not said to be complete");
1904                    }
1905
1906                    break;
1907                }
1908                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1909                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1910                            mInstantAppResolverConnection,
1911                            (InstantAppRequest) msg.obj,
1912                            mInstantAppInstallerActivity,
1913                            mHandler);
1914                }
1915            }
1916        }
1917    }
1918
1919    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1920            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1921            boolean launchedForRestore, String installerPackage,
1922            IPackageInstallObserver2 installObserver) {
1923        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1924            // Send the removed broadcasts
1925            if (res.removedInfo != null) {
1926                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1927            }
1928
1929            // Now that we successfully installed the package, grant runtime
1930            // permissions if requested before broadcasting the install. Also
1931            // for legacy apps in permission review mode we clear the permission
1932            // review flag which is used to emulate runtime permissions for
1933            // legacy apps.
1934            if (grantPermissions) {
1935                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1936            }
1937
1938            final boolean update = res.removedInfo != null
1939                    && res.removedInfo.removedPackage != null;
1940            final String installerPackageName =
1941                    res.installerPackageName != null
1942                            ? res.installerPackageName
1943                            : res.removedInfo != null
1944                                    ? res.removedInfo.installerPackageName
1945                                    : null;
1946
1947            // If this is the first time we have child packages for a disabled privileged
1948            // app that had no children, we grant requested runtime permissions to the new
1949            // children if the parent on the system image had them already granted.
1950            if (res.pkg.parentPackage != null) {
1951                synchronized (mPackages) {
1952                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1953                }
1954            }
1955
1956            synchronized (mPackages) {
1957                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1958            }
1959
1960            final String packageName = res.pkg.applicationInfo.packageName;
1961
1962            // Determine the set of users who are adding this package for
1963            // the first time vs. those who are seeing an update.
1964            int[] firstUsers = EMPTY_INT_ARRAY;
1965            int[] updateUsers = EMPTY_INT_ARRAY;
1966            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1967            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1968            for (int newUser : res.newUsers) {
1969                if (ps.getInstantApp(newUser)) {
1970                    continue;
1971                }
1972                if (allNewUsers) {
1973                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1974                    continue;
1975                }
1976                boolean isNew = true;
1977                for (int origUser : res.origUsers) {
1978                    if (origUser == newUser) {
1979                        isNew = false;
1980                        break;
1981                    }
1982                }
1983                if (isNew) {
1984                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1985                } else {
1986                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1987                }
1988            }
1989
1990            // Send installed broadcasts if the package is not a static shared lib.
1991            if (res.pkg.staticSharedLibName == null) {
1992                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1993
1994                // Send added for users that see the package for the first time
1995                // sendPackageAddedForNewUsers also deals with system apps
1996                int appId = UserHandle.getAppId(res.uid);
1997                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1998                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1999                        virtualPreload /*startReceiver*/, appId, firstUsers);
2000
2001                // Send added for users that don't see the package for the first time
2002                Bundle extras = new Bundle(1);
2003                extras.putInt(Intent.EXTRA_UID, res.uid);
2004                if (update) {
2005                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2006                }
2007                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2008                        extras, 0 /*flags*/,
2009                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2010                if (installerPackageName != null) {
2011                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2012                            extras, 0 /*flags*/,
2013                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2014                }
2015
2016                // Send replaced for users that don't see the package for the first time
2017                if (update) {
2018                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2019                            packageName, extras, 0 /*flags*/,
2020                            null /*targetPackage*/, null /*finishedReceiver*/,
2021                            updateUsers);
2022                    if (installerPackageName != null) {
2023                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2024                                extras, 0 /*flags*/,
2025                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2026                    }
2027                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2028                            null /*package*/, null /*extras*/, 0 /*flags*/,
2029                            packageName /*targetPackage*/,
2030                            null /*finishedReceiver*/, updateUsers);
2031                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2032                    // First-install and we did a restore, so we're responsible for the
2033                    // first-launch broadcast.
2034                    if (DEBUG_BACKUP) {
2035                        Slog.i(TAG, "Post-restore of " + packageName
2036                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2037                    }
2038                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2039                }
2040
2041                // Send broadcast package appeared if forward locked/external for all users
2042                // treat asec-hosted packages like removable media on upgrade
2043                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2044                    if (DEBUG_INSTALL) {
2045                        Slog.i(TAG, "upgrading pkg " + res.pkg
2046                                + " is ASEC-hosted -> AVAILABLE");
2047                    }
2048                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2049                    ArrayList<String> pkgList = new ArrayList<>(1);
2050                    pkgList.add(packageName);
2051                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2052                }
2053            }
2054
2055            // Work that needs to happen on first install within each user
2056            if (firstUsers != null && firstUsers.length > 0) {
2057                synchronized (mPackages) {
2058                    for (int userId : firstUsers) {
2059                        // If this app is a browser and it's newly-installed for some
2060                        // users, clear any default-browser state in those users. The
2061                        // app's nature doesn't depend on the user, so we can just check
2062                        // its browser nature in any user and generalize.
2063                        if (packageIsBrowser(packageName, userId)) {
2064                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2065                        }
2066
2067                        // We may also need to apply pending (restored) runtime
2068                        // permission grants within these users.
2069                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2070                    }
2071                }
2072            }
2073
2074            // Log current value of "unknown sources" setting
2075            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2076                    getUnknownSourcesSettings());
2077
2078            // Remove the replaced package's older resources safely now
2079            // We delete after a gc for applications  on sdcard.
2080            if (res.removedInfo != null && res.removedInfo.args != null) {
2081                Runtime.getRuntime().gc();
2082                synchronized (mInstallLock) {
2083                    res.removedInfo.args.doPostDeleteLI(true);
2084                }
2085            } else {
2086                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2087                // and not block here.
2088                VMRuntime.getRuntime().requestConcurrentGC();
2089            }
2090
2091            // Notify DexManager that the package was installed for new users.
2092            // The updated users should already be indexed and the package code paths
2093            // should not change.
2094            // Don't notify the manager for ephemeral apps as they are not expected to
2095            // survive long enough to benefit of background optimizations.
2096            for (int userId : firstUsers) {
2097                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2098                // There's a race currently where some install events may interleave with an uninstall.
2099                // This can lead to package info being null (b/36642664).
2100                if (info != null) {
2101                    mDexManager.notifyPackageInstalled(info, userId);
2102                }
2103            }
2104        }
2105
2106        // If someone is watching installs - notify them
2107        if (installObserver != null) {
2108            try {
2109                Bundle extras = extrasForInstallResult(res);
2110                installObserver.onPackageInstalled(res.name, res.returnCode,
2111                        res.returnMsg, extras);
2112            } catch (RemoteException e) {
2113                Slog.i(TAG, "Observer no longer exists.");
2114            }
2115        }
2116    }
2117
2118    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2119            PackageParser.Package pkg) {
2120        if (pkg.parentPackage == null) {
2121            return;
2122        }
2123        if (pkg.requestedPermissions == null) {
2124            return;
2125        }
2126        final PackageSetting disabledSysParentPs = mSettings
2127                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2128        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2129                || !disabledSysParentPs.isPrivileged()
2130                || (disabledSysParentPs.childPackageNames != null
2131                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2132            return;
2133        }
2134        final int[] allUserIds = sUserManager.getUserIds();
2135        final int permCount = pkg.requestedPermissions.size();
2136        for (int i = 0; i < permCount; i++) {
2137            String permission = pkg.requestedPermissions.get(i);
2138            BasePermission bp = mSettings.mPermissions.get(permission);
2139            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2140                continue;
2141            }
2142            for (int userId : allUserIds) {
2143                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2144                        permission, userId)) {
2145                    grantRuntimePermission(pkg.packageName, permission, userId);
2146                }
2147            }
2148        }
2149    }
2150
2151    private StorageEventListener mStorageListener = new StorageEventListener() {
2152        @Override
2153        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2154            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2155                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2156                    final String volumeUuid = vol.getFsUuid();
2157
2158                    // Clean up any users or apps that were removed or recreated
2159                    // while this volume was missing
2160                    sUserManager.reconcileUsers(volumeUuid);
2161                    reconcileApps(volumeUuid);
2162
2163                    // Clean up any install sessions that expired or were
2164                    // cancelled while this volume was missing
2165                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2166
2167                    loadPrivatePackages(vol);
2168
2169                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2170                    unloadPrivatePackages(vol);
2171                }
2172            }
2173
2174            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2175                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2176                    updateExternalMediaStatus(true, false);
2177                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2178                    updateExternalMediaStatus(false, false);
2179                }
2180            }
2181        }
2182
2183        @Override
2184        public void onVolumeForgotten(String fsUuid) {
2185            if (TextUtils.isEmpty(fsUuid)) {
2186                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2187                return;
2188            }
2189
2190            // Remove any apps installed on the forgotten volume
2191            synchronized (mPackages) {
2192                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2193                for (PackageSetting ps : packages) {
2194                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2195                    deletePackageVersioned(new VersionedPackage(ps.name,
2196                            PackageManager.VERSION_CODE_HIGHEST),
2197                            new LegacyPackageDeleteObserver(null).getBinder(),
2198                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2199                    // Try very hard to release any references to this package
2200                    // so we don't risk the system server being killed due to
2201                    // open FDs
2202                    AttributeCache.instance().removePackage(ps.name);
2203                }
2204
2205                mSettings.onVolumeForgotten(fsUuid);
2206                mSettings.writeLPr();
2207            }
2208        }
2209    };
2210
2211    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2212            String[] grantedPermissions) {
2213        for (int userId : userIds) {
2214            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2215        }
2216    }
2217
2218    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2219            String[] grantedPermissions) {
2220        PackageSetting ps = (PackageSetting) pkg.mExtras;
2221        if (ps == null) {
2222            return;
2223        }
2224
2225        PermissionsState permissionsState = ps.getPermissionsState();
2226
2227        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2228                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2229
2230        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2231                >= Build.VERSION_CODES.M;
2232
2233        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2234
2235        for (String permission : pkg.requestedPermissions) {
2236            final BasePermission bp;
2237            synchronized (mPackages) {
2238                bp = mSettings.mPermissions.get(permission);
2239            }
2240            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2241                    && (!instantApp || bp.isInstant())
2242                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2243                    && (grantedPermissions == null
2244                           || ArrayUtils.contains(grantedPermissions, permission))) {
2245                final int flags = permissionsState.getPermissionFlags(permission, userId);
2246                if (supportsRuntimePermissions) {
2247                    // Installer cannot change immutable permissions.
2248                    if ((flags & immutableFlags) == 0) {
2249                        grantRuntimePermission(pkg.packageName, permission, userId);
2250                    }
2251                } else if (mPermissionReviewRequired) {
2252                    // In permission review mode we clear the review flag when we
2253                    // are asked to install the app with all permissions granted.
2254                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2255                        updatePermissionFlags(permission, pkg.packageName,
2256                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2257                    }
2258                }
2259            }
2260        }
2261    }
2262
2263    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2264        Bundle extras = null;
2265        switch (res.returnCode) {
2266            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2267                extras = new Bundle();
2268                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2269                        res.origPermission);
2270                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2271                        res.origPackage);
2272                break;
2273            }
2274            case PackageManager.INSTALL_SUCCEEDED: {
2275                extras = new Bundle();
2276                extras.putBoolean(Intent.EXTRA_REPLACING,
2277                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2278                break;
2279            }
2280        }
2281        return extras;
2282    }
2283
2284    void scheduleWriteSettingsLocked() {
2285        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2286            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2287        }
2288    }
2289
2290    void scheduleWritePackageListLocked(int userId) {
2291        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2292            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2293            msg.arg1 = userId;
2294            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2295        }
2296    }
2297
2298    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2299        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2300        scheduleWritePackageRestrictionsLocked(userId);
2301    }
2302
2303    void scheduleWritePackageRestrictionsLocked(int userId) {
2304        final int[] userIds = (userId == UserHandle.USER_ALL)
2305                ? sUserManager.getUserIds() : new int[]{userId};
2306        for (int nextUserId : userIds) {
2307            if (!sUserManager.exists(nextUserId)) return;
2308            mDirtyUsers.add(nextUserId);
2309            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2310                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2311            }
2312        }
2313    }
2314
2315    public static PackageManagerService main(Context context, Installer installer,
2316            boolean factoryTest, boolean onlyCore) {
2317        // Self-check for initial settings.
2318        PackageManagerServiceCompilerMapping.checkProperties();
2319
2320        PackageManagerService m = new PackageManagerService(context, installer,
2321                factoryTest, onlyCore);
2322        m.enableSystemUserPackages();
2323        ServiceManager.addService("package", m);
2324        final PackageManagerNative pmn = m.new PackageManagerNative();
2325        ServiceManager.addService("package_native", pmn);
2326        return m;
2327    }
2328
2329    private void enableSystemUserPackages() {
2330        if (!UserManager.isSplitSystemUser()) {
2331            return;
2332        }
2333        // For system user, enable apps based on the following conditions:
2334        // - app is whitelisted or belong to one of these groups:
2335        //   -- system app which has no launcher icons
2336        //   -- system app which has INTERACT_ACROSS_USERS permission
2337        //   -- system IME app
2338        // - app is not in the blacklist
2339        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2340        Set<String> enableApps = new ArraySet<>();
2341        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2342                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2343                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2344        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2345        enableApps.addAll(wlApps);
2346        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2347                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2348        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2349        enableApps.removeAll(blApps);
2350        Log.i(TAG, "Applications installed for system user: " + enableApps);
2351        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2352                UserHandle.SYSTEM);
2353        final int allAppsSize = allAps.size();
2354        synchronized (mPackages) {
2355            for (int i = 0; i < allAppsSize; i++) {
2356                String pName = allAps.get(i);
2357                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2358                // Should not happen, but we shouldn't be failing if it does
2359                if (pkgSetting == null) {
2360                    continue;
2361                }
2362                boolean install = enableApps.contains(pName);
2363                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2364                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2365                            + " for system user");
2366                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2367                }
2368            }
2369            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2370        }
2371    }
2372
2373    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2374        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2375                Context.DISPLAY_SERVICE);
2376        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2377    }
2378
2379    /**
2380     * Requests that files preopted on a secondary system partition be copied to the data partition
2381     * if possible.  Note that the actual copying of the files is accomplished by init for security
2382     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2383     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2384     */
2385    private static void requestCopyPreoptedFiles() {
2386        final int WAIT_TIME_MS = 100;
2387        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2388        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2389            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2390            // We will wait for up to 100 seconds.
2391            final long timeStart = SystemClock.uptimeMillis();
2392            final long timeEnd = timeStart + 100 * 1000;
2393            long timeNow = timeStart;
2394            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2395                try {
2396                    Thread.sleep(WAIT_TIME_MS);
2397                } catch (InterruptedException e) {
2398                    // Do nothing
2399                }
2400                timeNow = SystemClock.uptimeMillis();
2401                if (timeNow > timeEnd) {
2402                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2403                    Slog.wtf(TAG, "cppreopt did not finish!");
2404                    break;
2405                }
2406            }
2407
2408            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2409        }
2410    }
2411
2412    public PackageManagerService(Context context, Installer installer,
2413            boolean factoryTest, boolean onlyCore) {
2414        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2415        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2416        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2417                SystemClock.uptimeMillis());
2418
2419        if (mSdkVersion <= 0) {
2420            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2421        }
2422
2423        mContext = context;
2424
2425        mPermissionReviewRequired = context.getResources().getBoolean(
2426                R.bool.config_permissionReviewRequired);
2427
2428        mFactoryTest = factoryTest;
2429        mOnlyCore = onlyCore;
2430        mMetrics = new DisplayMetrics();
2431        mSettings = new Settings(mPackages);
2432        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2433                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2434        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2435                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2436        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2437                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2438        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2439                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2440        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2441                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2442        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2443                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2444        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2445                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2446
2447        String separateProcesses = SystemProperties.get("debug.separate_processes");
2448        if (separateProcesses != null && separateProcesses.length() > 0) {
2449            if ("*".equals(separateProcesses)) {
2450                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2451                mSeparateProcesses = null;
2452                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2453            } else {
2454                mDefParseFlags = 0;
2455                mSeparateProcesses = separateProcesses.split(",");
2456                Slog.w(TAG, "Running with debug.separate_processes: "
2457                        + separateProcesses);
2458            }
2459        } else {
2460            mDefParseFlags = 0;
2461            mSeparateProcesses = null;
2462        }
2463
2464        mInstaller = installer;
2465        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2466                "*dexopt*");
2467        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2468                installer, mInstallLock);
2469        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2470                dexManagerListener);
2471        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2472
2473        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2474                FgThread.get().getLooper());
2475
2476        getDefaultDisplayMetrics(context, mMetrics);
2477
2478        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2479        SystemConfig systemConfig = SystemConfig.getInstance();
2480        mGlobalGids = systemConfig.getGlobalGids();
2481        mSystemPermissions = systemConfig.getSystemPermissions();
2482        mAvailableFeatures = systemConfig.getAvailableFeatures();
2483        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2484
2485        mProtectedPackages = new ProtectedPackages(mContext);
2486
2487        synchronized (mInstallLock) {
2488        // writer
2489        synchronized (mPackages) {
2490            mHandlerThread = new ServiceThread(TAG,
2491                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2492            mHandlerThread.start();
2493            mHandler = new PackageHandler(mHandlerThread.getLooper());
2494            mProcessLoggingHandler = new ProcessLoggingHandler();
2495            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2496
2497            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2498            mInstantAppRegistry = new InstantAppRegistry(this);
2499
2500            File dataDir = Environment.getDataDirectory();
2501            mAppInstallDir = new File(dataDir, "app");
2502            mAppLib32InstallDir = new File(dataDir, "app-lib");
2503            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2504            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2505            sUserManager = new UserManagerService(context, this,
2506                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2507
2508            // Propagate permission configuration in to package manager.
2509            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2510                    = systemConfig.getPermissions();
2511            for (int i=0; i<permConfig.size(); i++) {
2512                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2513                BasePermission bp = mSettings.mPermissions.get(perm.name);
2514                if (bp == null) {
2515                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2516                    mSettings.mPermissions.put(perm.name, bp);
2517                }
2518                if (perm.gids != null) {
2519                    bp.setGids(perm.gids, perm.perUser);
2520                }
2521            }
2522
2523            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2524            final int builtInLibCount = libConfig.size();
2525            for (int i = 0; i < builtInLibCount; i++) {
2526                String name = libConfig.keyAt(i);
2527                String path = libConfig.valueAt(i);
2528                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2529                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2530            }
2531
2532            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2533
2534            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2535            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2536            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2537
2538            // Clean up orphaned packages for which the code path doesn't exist
2539            // and they are an update to a system app - caused by bug/32321269
2540            final int packageSettingCount = mSettings.mPackages.size();
2541            for (int i = packageSettingCount - 1; i >= 0; i--) {
2542                PackageSetting ps = mSettings.mPackages.valueAt(i);
2543                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2544                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2545                    mSettings.mPackages.removeAt(i);
2546                    mSettings.enableSystemPackageLPw(ps.name);
2547                }
2548            }
2549
2550            if (mFirstBoot) {
2551                requestCopyPreoptedFiles();
2552            }
2553
2554            String customResolverActivity = Resources.getSystem().getString(
2555                    R.string.config_customResolverActivity);
2556            if (TextUtils.isEmpty(customResolverActivity)) {
2557                customResolverActivity = null;
2558            } else {
2559                mCustomResolverComponentName = ComponentName.unflattenFromString(
2560                        customResolverActivity);
2561            }
2562
2563            long startTime = SystemClock.uptimeMillis();
2564
2565            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2566                    startTime);
2567
2568            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2569            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2570
2571            if (bootClassPath == null) {
2572                Slog.w(TAG, "No BOOTCLASSPATH found!");
2573            }
2574
2575            if (systemServerClassPath == null) {
2576                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2577            }
2578
2579            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2580
2581            final VersionInfo ver = mSettings.getInternalVersion();
2582            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2583            if (mIsUpgrade) {
2584                logCriticalInfo(Log.INFO,
2585                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2586            }
2587
2588            // when upgrading from pre-M, promote system app permissions from install to runtime
2589            mPromoteSystemApps =
2590                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2591
2592            // When upgrading from pre-N, we need to handle package extraction like first boot,
2593            // as there is no profiling data available.
2594            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2595
2596            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2597
2598            // save off the names of pre-existing system packages prior to scanning; we don't
2599            // want to automatically grant runtime permissions for new system apps
2600            if (mPromoteSystemApps) {
2601                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2602                while (pkgSettingIter.hasNext()) {
2603                    PackageSetting ps = pkgSettingIter.next();
2604                    if (isSystemApp(ps)) {
2605                        mExistingSystemPackages.add(ps.name);
2606                    }
2607                }
2608            }
2609
2610            mCacheDir = preparePackageParserCache(mIsUpgrade);
2611
2612            // Set flag to monitor and not change apk file paths when
2613            // scanning install directories.
2614            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2615
2616            if (mIsUpgrade || mFirstBoot) {
2617                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2618            }
2619
2620            // Collect vendor overlay packages. (Do this before scanning any apps.)
2621            // For security and version matching reason, only consider
2622            // overlay packages if they reside in the right directory.
2623            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2624                    | PackageParser.PARSE_IS_SYSTEM
2625                    | PackageParser.PARSE_IS_SYSTEM_DIR
2626                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2627
2628            mParallelPackageParserCallback.findStaticOverlayPackages();
2629
2630            // Find base frameworks (resource packages without code).
2631            scanDirTracedLI(frameworkDir, mDefParseFlags
2632                    | PackageParser.PARSE_IS_SYSTEM
2633                    | PackageParser.PARSE_IS_SYSTEM_DIR
2634                    | PackageParser.PARSE_IS_PRIVILEGED,
2635                    scanFlags | SCAN_NO_DEX, 0);
2636
2637            // Collected privileged system packages.
2638            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2639            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2640                    | PackageParser.PARSE_IS_SYSTEM
2641                    | PackageParser.PARSE_IS_SYSTEM_DIR
2642                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2643
2644            // Collect ordinary system packages.
2645            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2646            scanDirTracedLI(systemAppDir, mDefParseFlags
2647                    | PackageParser.PARSE_IS_SYSTEM
2648                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2649
2650            // Collect all vendor packages.
2651            File vendorAppDir = new File("/vendor/app");
2652            try {
2653                vendorAppDir = vendorAppDir.getCanonicalFile();
2654            } catch (IOException e) {
2655                // failed to look up canonical path, continue with original one
2656            }
2657            scanDirTracedLI(vendorAppDir, mDefParseFlags
2658                    | PackageParser.PARSE_IS_SYSTEM
2659                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2660
2661            // Collect all OEM packages.
2662            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2663            scanDirTracedLI(oemAppDir, mDefParseFlags
2664                    | PackageParser.PARSE_IS_SYSTEM
2665                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2666
2667            // Prune any system packages that no longer exist.
2668            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2669            // Stub packages must either be replaced with full versions in the /data
2670            // partition or be disabled.
2671            final List<String> stubSystemApps = new ArrayList<>();
2672            if (!mOnlyCore) {
2673                // do this first before mucking with mPackages for the "expecting better" case
2674                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2675                while (pkgIterator.hasNext()) {
2676                    final PackageParser.Package pkg = pkgIterator.next();
2677                    if (pkg.isStub) {
2678                        stubSystemApps.add(pkg.packageName);
2679                    }
2680                }
2681
2682                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2683                while (psit.hasNext()) {
2684                    PackageSetting ps = psit.next();
2685
2686                    /*
2687                     * If this is not a system app, it can't be a
2688                     * disable system app.
2689                     */
2690                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2691                        continue;
2692                    }
2693
2694                    /*
2695                     * If the package is scanned, it's not erased.
2696                     */
2697                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2698                    if (scannedPkg != null) {
2699                        /*
2700                         * If the system app is both scanned and in the
2701                         * disabled packages list, then it must have been
2702                         * added via OTA. Remove it from the currently
2703                         * scanned package so the previously user-installed
2704                         * application can be scanned.
2705                         */
2706                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2707                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2708                                    + ps.name + "; removing system app.  Last known codePath="
2709                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2710                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2711                                    + scannedPkg.mVersionCode);
2712                            removePackageLI(scannedPkg, true);
2713                            mExpectingBetter.put(ps.name, ps.codePath);
2714                        }
2715
2716                        continue;
2717                    }
2718
2719                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2720                        psit.remove();
2721                        logCriticalInfo(Log.WARN, "System package " + ps.name
2722                                + " no longer exists; it's data will be wiped");
2723                        // Actual deletion of code and data will be handled by later
2724                        // reconciliation step
2725                    } else {
2726                        // we still have a disabled system package, but, it still might have
2727                        // been removed. check the code path still exists and check there's
2728                        // still a package. the latter can happen if an OTA keeps the same
2729                        // code path, but, changes the package name.
2730                        final PackageSetting disabledPs =
2731                                mSettings.getDisabledSystemPkgLPr(ps.name);
2732                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2733                                || disabledPs.pkg == null) {
2734                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2735                        }
2736                    }
2737                }
2738            }
2739
2740            //look for any incomplete package installations
2741            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2742            for (int i = 0; i < deletePkgsList.size(); i++) {
2743                // Actual deletion of code and data will be handled by later
2744                // reconciliation step
2745                final String packageName = deletePkgsList.get(i).name;
2746                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2747                synchronized (mPackages) {
2748                    mSettings.removePackageLPw(packageName);
2749                }
2750            }
2751
2752            //delete tmp files
2753            deleteTempPackageFiles();
2754
2755            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2756
2757            // Remove any shared userIDs that have no associated packages
2758            mSettings.pruneSharedUsersLPw();
2759            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2760            final int systemPackagesCount = mPackages.size();
2761            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2762                    + " ms, packageCount: " + systemPackagesCount
2763                    + " , timePerPackage: "
2764                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2765                    + " , cached: " + cachedSystemApps);
2766            if (mIsUpgrade && systemPackagesCount > 0) {
2767                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2768                        ((int) systemScanTime) / systemPackagesCount);
2769            }
2770            if (!mOnlyCore) {
2771                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2772                        SystemClock.uptimeMillis());
2773                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2774
2775                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2776                        | PackageParser.PARSE_FORWARD_LOCK,
2777                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2778
2779                // Remove disable package settings for updated system apps that were
2780                // removed via an OTA. If the update is no longer present, remove the
2781                // app completely. Otherwise, revoke their system privileges.
2782                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2783                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2784                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2785
2786                    final String msg;
2787                    if (deletedPkg == null) {
2788                        // should have found an update, but, we didn't; remove everything
2789                        msg = "Updated system package " + deletedAppName
2790                                + " no longer exists; removing its data";
2791                        // Actual deletion of code and data will be handled by later
2792                        // reconciliation step
2793                    } else {
2794                        // found an update; revoke system privileges
2795                        msg = "Updated system package + " + deletedAppName
2796                                + " no longer exists; revoking system privileges";
2797
2798                        // Don't do anything if a stub is removed from the system image. If
2799                        // we were to remove the uncompressed version from the /data partition,
2800                        // this is where it'd be done.
2801
2802                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2803                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2804                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2805                    }
2806                    logCriticalInfo(Log.WARN, msg);
2807                }
2808
2809                /*
2810                 * Make sure all system apps that we expected to appear on
2811                 * the userdata partition actually showed up. If they never
2812                 * appeared, crawl back and revive the system version.
2813                 */
2814                for (int i = 0; i < mExpectingBetter.size(); i++) {
2815                    final String packageName = mExpectingBetter.keyAt(i);
2816                    if (!mPackages.containsKey(packageName)) {
2817                        final File scanFile = mExpectingBetter.valueAt(i);
2818
2819                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2820                                + " but never showed up; reverting to system");
2821
2822                        int reparseFlags = mDefParseFlags;
2823                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2824                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2825                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2826                                    | PackageParser.PARSE_IS_PRIVILEGED;
2827                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2828                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2829                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2830                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2831                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2832                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2833                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2834                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2835                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2836                        } else {
2837                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2838                            continue;
2839                        }
2840
2841                        mSettings.enableSystemPackageLPw(packageName);
2842
2843                        try {
2844                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2845                        } catch (PackageManagerException e) {
2846                            Slog.e(TAG, "Failed to parse original system package: "
2847                                    + e.getMessage());
2848                        }
2849                    }
2850                }
2851
2852                // Uncompress and install any stubbed system applications.
2853                // This must be done last to ensure all stubs are replaced or disabled.
2854                decompressSystemApplications(stubSystemApps, scanFlags);
2855
2856                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2857                                - cachedSystemApps;
2858
2859                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2860                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2861                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2862                        + " ms, packageCount: " + dataPackagesCount
2863                        + " , timePerPackage: "
2864                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2865                        + " , cached: " + cachedNonSystemApps);
2866                if (mIsUpgrade && dataPackagesCount > 0) {
2867                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2868                            ((int) dataScanTime) / dataPackagesCount);
2869                }
2870            }
2871            mExpectingBetter.clear();
2872
2873            // Resolve the storage manager.
2874            mStorageManagerPackage = getStorageManagerPackageName();
2875
2876            // Resolve protected action filters. Only the setup wizard is allowed to
2877            // have a high priority filter for these actions.
2878            mSetupWizardPackage = getSetupWizardPackageName();
2879            if (mProtectedFilters.size() > 0) {
2880                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2881                    Slog.i(TAG, "No setup wizard;"
2882                        + " All protected intents capped to priority 0");
2883                }
2884                for (ActivityIntentInfo filter : mProtectedFilters) {
2885                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2886                        if (DEBUG_FILTERS) {
2887                            Slog.i(TAG, "Found setup wizard;"
2888                                + " allow priority " + filter.getPriority() + ";"
2889                                + " package: " + filter.activity.info.packageName
2890                                + " activity: " + filter.activity.className
2891                                + " priority: " + filter.getPriority());
2892                        }
2893                        // skip setup wizard; allow it to keep the high priority filter
2894                        continue;
2895                    }
2896                    if (DEBUG_FILTERS) {
2897                        Slog.i(TAG, "Protected action; cap priority to 0;"
2898                                + " package: " + filter.activity.info.packageName
2899                                + " activity: " + filter.activity.className
2900                                + " origPrio: " + filter.getPriority());
2901                    }
2902                    filter.setPriority(0);
2903                }
2904            }
2905            mDeferProtectedFilters = false;
2906            mProtectedFilters.clear();
2907
2908            // Now that we know all of the shared libraries, update all clients to have
2909            // the correct library paths.
2910            updateAllSharedLibrariesLPw(null);
2911
2912            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2913                // NOTE: We ignore potential failures here during a system scan (like
2914                // the rest of the commands above) because there's precious little we
2915                // can do about it. A settings error is reported, though.
2916                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2917            }
2918
2919            // Now that we know all the packages we are keeping,
2920            // read and update their last usage times.
2921            mPackageUsage.read(mPackages);
2922            mCompilerStats.read();
2923
2924            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2925                    SystemClock.uptimeMillis());
2926            Slog.i(TAG, "Time to scan packages: "
2927                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2928                    + " seconds");
2929
2930            // If the platform SDK has changed since the last time we booted,
2931            // we need to re-grant app permission to catch any new ones that
2932            // appear.  This is really a hack, and means that apps can in some
2933            // cases get permissions that the user didn't initially explicitly
2934            // allow...  it would be nice to have some better way to handle
2935            // this situation.
2936            int updateFlags = UPDATE_PERMISSIONS_ALL;
2937            if (ver.sdkVersion != mSdkVersion) {
2938                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2939                        + mSdkVersion + "; regranting permissions for internal storage");
2940                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2941            }
2942            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2943            ver.sdkVersion = mSdkVersion;
2944
2945            // If this is the first boot or an update from pre-M, and it is a normal
2946            // boot, then we need to initialize the default preferred apps across
2947            // all defined users.
2948            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2949                for (UserInfo user : sUserManager.getUsers(true)) {
2950                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2951                    applyFactoryDefaultBrowserLPw(user.id);
2952                    primeDomainVerificationsLPw(user.id);
2953                }
2954            }
2955
2956            // Prepare storage for system user really early during boot,
2957            // since core system apps like SettingsProvider and SystemUI
2958            // can't wait for user to start
2959            final int storageFlags;
2960            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2961                storageFlags = StorageManager.FLAG_STORAGE_DE;
2962            } else {
2963                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2964            }
2965            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2966                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2967                    true /* onlyCoreApps */);
2968            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2969                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2970                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2971                traceLog.traceBegin("AppDataFixup");
2972                try {
2973                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2974                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2975                } catch (InstallerException e) {
2976                    Slog.w(TAG, "Trouble fixing GIDs", e);
2977                }
2978                traceLog.traceEnd();
2979
2980                traceLog.traceBegin("AppDataPrepare");
2981                if (deferPackages == null || deferPackages.isEmpty()) {
2982                    return;
2983                }
2984                int count = 0;
2985                for (String pkgName : deferPackages) {
2986                    PackageParser.Package pkg = null;
2987                    synchronized (mPackages) {
2988                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2989                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2990                            pkg = ps.pkg;
2991                        }
2992                    }
2993                    if (pkg != null) {
2994                        synchronized (mInstallLock) {
2995                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2996                                    true /* maybeMigrateAppData */);
2997                        }
2998                        count++;
2999                    }
3000                }
3001                traceLog.traceEnd();
3002                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3003            }, "prepareAppData");
3004
3005            // If this is first boot after an OTA, and a normal boot, then
3006            // we need to clear code cache directories.
3007            // Note that we do *not* clear the application profiles. These remain valid
3008            // across OTAs and are used to drive profile verification (post OTA) and
3009            // profile compilation (without waiting to collect a fresh set of profiles).
3010            if (mIsUpgrade && !onlyCore) {
3011                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3012                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3013                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3014                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3015                        // No apps are running this early, so no need to freeze
3016                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3017                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3018                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3019                    }
3020                }
3021                ver.fingerprint = Build.FINGERPRINT;
3022            }
3023
3024            checkDefaultBrowser();
3025
3026            // clear only after permissions and other defaults have been updated
3027            mExistingSystemPackages.clear();
3028            mPromoteSystemApps = false;
3029
3030            // All the changes are done during package scanning.
3031            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3032
3033            // can downgrade to reader
3034            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3035            mSettings.writeLPr();
3036            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3037            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3038                    SystemClock.uptimeMillis());
3039
3040            if (!mOnlyCore) {
3041                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3042                mRequiredInstallerPackage = getRequiredInstallerLPr();
3043                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3044                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3045                if (mIntentFilterVerifierComponent != null) {
3046                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3047                            mIntentFilterVerifierComponent);
3048                } else {
3049                    mIntentFilterVerifier = null;
3050                }
3051                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3052                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3053                        SharedLibraryInfo.VERSION_UNDEFINED);
3054                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3055                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3056                        SharedLibraryInfo.VERSION_UNDEFINED);
3057            } else {
3058                mRequiredVerifierPackage = null;
3059                mRequiredInstallerPackage = null;
3060                mRequiredUninstallerPackage = null;
3061                mIntentFilterVerifierComponent = null;
3062                mIntentFilterVerifier = null;
3063                mServicesSystemSharedLibraryPackageName = null;
3064                mSharedSystemSharedLibraryPackageName = null;
3065            }
3066
3067            mInstallerService = new PackageInstallerService(context, this);
3068            mArtManagerService = new ArtManagerService(this, mInstaller, mInstallLock);
3069            final Pair<ComponentName, String> instantAppResolverComponent =
3070                    getInstantAppResolverLPr();
3071            if (instantAppResolverComponent != null) {
3072                if (DEBUG_EPHEMERAL) {
3073                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3074                }
3075                mInstantAppResolverConnection = new EphemeralResolverConnection(
3076                        mContext, instantAppResolverComponent.first,
3077                        instantAppResolverComponent.second);
3078                mInstantAppResolverSettingsComponent =
3079                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3080            } else {
3081                mInstantAppResolverConnection = null;
3082                mInstantAppResolverSettingsComponent = null;
3083            }
3084            updateInstantAppInstallerLocked(null);
3085
3086            // Read and update the usage of dex files.
3087            // Do this at the end of PM init so that all the packages have their
3088            // data directory reconciled.
3089            // At this point we know the code paths of the packages, so we can validate
3090            // the disk file and build the internal cache.
3091            // The usage file is expected to be small so loading and verifying it
3092            // should take a fairly small time compare to the other activities (e.g. package
3093            // scanning).
3094            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3095            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3096            for (int userId : currentUserIds) {
3097                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3098            }
3099            mDexManager.load(userPackages);
3100            if (mIsUpgrade) {
3101                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3102                        (int) (SystemClock.uptimeMillis() - startTime));
3103            }
3104        } // synchronized (mPackages)
3105        } // synchronized (mInstallLock)
3106
3107        // Now after opening every single application zip, make sure they
3108        // are all flushed.  Not really needed, but keeps things nice and
3109        // tidy.
3110        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3111        Runtime.getRuntime().gc();
3112        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3113
3114        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3115        FallbackCategoryProvider.loadFallbacks();
3116        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3117
3118        // The initial scanning above does many calls into installd while
3119        // holding the mPackages lock, but we're mostly interested in yelling
3120        // once we have a booted system.
3121        mInstaller.setWarnIfHeld(mPackages);
3122
3123        // Expose private service for system components to use.
3124        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3125        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3126    }
3127
3128    /**
3129     * Uncompress and install stub applications.
3130     * <p>In order to save space on the system partition, some applications are shipped in a
3131     * compressed form. In addition the compressed bits for the full application, the
3132     * system image contains a tiny stub comprised of only the Android manifest.
3133     * <p>During the first boot, attempt to uncompress and install the full application. If
3134     * the application can't be installed for any reason, disable the stub and prevent
3135     * uncompressing the full application during future boots.
3136     * <p>In order to forcefully attempt an installation of a full application, go to app
3137     * settings and enable the application.
3138     */
3139    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3140        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3141            final String pkgName = stubSystemApps.get(i);
3142            // skip if the system package is already disabled
3143            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3144                stubSystemApps.remove(i);
3145                continue;
3146            }
3147            // skip if the package isn't installed (?!); this should never happen
3148            final PackageParser.Package pkg = mPackages.get(pkgName);
3149            if (pkg == null) {
3150                stubSystemApps.remove(i);
3151                continue;
3152            }
3153            // skip if the package has been disabled by the user
3154            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3155            if (ps != null) {
3156                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3157                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3158                    stubSystemApps.remove(i);
3159                    continue;
3160                }
3161            }
3162
3163            if (DEBUG_COMPRESSION) {
3164                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3165            }
3166
3167            // uncompress the binary to its eventual destination on /data
3168            final File scanFile = decompressPackage(pkg);
3169            if (scanFile == null) {
3170                continue;
3171            }
3172
3173            // install the package to replace the stub on /system
3174            try {
3175                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3176                removePackageLI(pkg, true /*chatty*/);
3177                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3178                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3179                        UserHandle.USER_SYSTEM, "android");
3180                stubSystemApps.remove(i);
3181                continue;
3182            } catch (PackageManagerException e) {
3183                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3184            }
3185
3186            // any failed attempt to install the package will be cleaned up later
3187        }
3188
3189        // disable any stub still left; these failed to install the full application
3190        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3191            final String pkgName = stubSystemApps.get(i);
3192            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3193            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3194                    UserHandle.USER_SYSTEM, "android");
3195            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3196        }
3197    }
3198
3199    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3200        if (DEBUG_COMPRESSION) {
3201            Slog.i(TAG, "Decompress file"
3202                    + "; src: " + srcFile.getAbsolutePath()
3203                    + ", dst: " + dstFile.getAbsolutePath());
3204        }
3205        try (
3206                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3207                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3208        ) {
3209            Streams.copy(fileIn, fileOut);
3210            Os.chmod(dstFile.getAbsolutePath(), 0644);
3211            return PackageManager.INSTALL_SUCCEEDED;
3212        } catch (IOException e) {
3213            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3214                    + "; src: " + srcFile.getAbsolutePath()
3215                    + ", dst: " + dstFile.getAbsolutePath());
3216        }
3217        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3218    }
3219
3220    private File[] getCompressedFiles(String codePath) {
3221        final File stubCodePath = new File(codePath);
3222        final String stubName = stubCodePath.getName();
3223
3224        // The layout of a compressed package on a given partition is as follows :
3225        //
3226        // Compressed artifacts:
3227        //
3228        // /partition/ModuleName/foo.gz
3229        // /partation/ModuleName/bar.gz
3230        //
3231        // Stub artifact:
3232        //
3233        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3234        //
3235        // In other words, stub is on the same partition as the compressed artifacts
3236        // and in a directory that's suffixed with "-Stub".
3237        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3238        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3239            return null;
3240        }
3241
3242        final File stubParentDir = stubCodePath.getParentFile();
3243        if (stubParentDir == null) {
3244            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3245            return null;
3246        }
3247
3248        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3249        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3250            @Override
3251            public boolean accept(File dir, String name) {
3252                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3253            }
3254        });
3255
3256        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3257            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3258        }
3259
3260        return files;
3261    }
3262
3263    private boolean compressedFileExists(String codePath) {
3264        final File[] compressedFiles = getCompressedFiles(codePath);
3265        return compressedFiles != null && compressedFiles.length > 0;
3266    }
3267
3268    /**
3269     * Decompresses the given package on the system image onto
3270     * the /data partition.
3271     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3272     */
3273    private File decompressPackage(PackageParser.Package pkg) {
3274        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3275        if (compressedFiles == null || compressedFiles.length == 0) {
3276            if (DEBUG_COMPRESSION) {
3277                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3278            }
3279            return null;
3280        }
3281        final File dstCodePath =
3282                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3283        int ret = PackageManager.INSTALL_SUCCEEDED;
3284        try {
3285            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3286            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3287            for (File srcFile : compressedFiles) {
3288                final String srcFileName = srcFile.getName();
3289                final String dstFileName = srcFileName.substring(
3290                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3291                final File dstFile = new File(dstCodePath, dstFileName);
3292                ret = decompressFile(srcFile, dstFile);
3293                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3294                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3295                            + "; pkg: " + pkg.packageName
3296                            + ", file: " + dstFileName);
3297                    break;
3298                }
3299            }
3300        } catch (ErrnoException e) {
3301            logCriticalInfo(Log.ERROR, "Failed to decompress"
3302                    + "; pkg: " + pkg.packageName
3303                    + ", err: " + e.errno);
3304        }
3305        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3306            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3307            NativeLibraryHelper.Handle handle = null;
3308            try {
3309                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3310                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3311                        null /*abiOverride*/);
3312            } catch (IOException e) {
3313                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3314                        + "; pkg: " + pkg.packageName);
3315                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3316            } finally {
3317                IoUtils.closeQuietly(handle);
3318            }
3319        }
3320        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3321            if (dstCodePath == null || !dstCodePath.exists()) {
3322                return null;
3323            }
3324            removeCodePathLI(dstCodePath);
3325            return null;
3326        }
3327
3328        return dstCodePath;
3329    }
3330
3331    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3332        // we're only interested in updating the installer appliction when 1) it's not
3333        // already set or 2) the modified package is the installer
3334        if (mInstantAppInstallerActivity != null
3335                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3336                        .equals(modifiedPackage)) {
3337            return;
3338        }
3339        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3340    }
3341
3342    private static File preparePackageParserCache(boolean isUpgrade) {
3343        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3344            return null;
3345        }
3346
3347        // Disable package parsing on eng builds to allow for faster incremental development.
3348        if (Build.IS_ENG) {
3349            return null;
3350        }
3351
3352        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3353            Slog.i(TAG, "Disabling package parser cache due to system property.");
3354            return null;
3355        }
3356
3357        // The base directory for the package parser cache lives under /data/system/.
3358        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3359                "package_cache");
3360        if (cacheBaseDir == null) {
3361            return null;
3362        }
3363
3364        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3365        // This also serves to "GC" unused entries when the package cache version changes (which
3366        // can only happen during upgrades).
3367        if (isUpgrade) {
3368            FileUtils.deleteContents(cacheBaseDir);
3369        }
3370
3371
3372        // Return the versioned package cache directory. This is something like
3373        // "/data/system/package_cache/1"
3374        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3375
3376        // The following is a workaround to aid development on non-numbered userdebug
3377        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3378        // the system partition is newer.
3379        //
3380        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3381        // that starts with "eng." to signify that this is an engineering build and not
3382        // destined for release.
3383        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3384            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3385
3386            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3387            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3388            // in general and should not be used for production changes. In this specific case,
3389            // we know that they will work.
3390            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3391            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3392                FileUtils.deleteContents(cacheBaseDir);
3393                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3394            }
3395        }
3396
3397        return cacheDir;
3398    }
3399
3400    @Override
3401    public boolean isFirstBoot() {
3402        // allow instant applications
3403        return mFirstBoot;
3404    }
3405
3406    @Override
3407    public boolean isOnlyCoreApps() {
3408        // allow instant applications
3409        return mOnlyCore;
3410    }
3411
3412    @Override
3413    public boolean isUpgrade() {
3414        // allow instant applications
3415        return mIsUpgrade;
3416    }
3417
3418    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3419        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3420
3421        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3422                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3423                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3424        if (matches.size() == 1) {
3425            return matches.get(0).getComponentInfo().packageName;
3426        } else if (matches.size() == 0) {
3427            Log.e(TAG, "There should probably be a verifier, but, none were found");
3428            return null;
3429        }
3430        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3431    }
3432
3433    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3434        synchronized (mPackages) {
3435            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3436            if (libraryEntry == null) {
3437                throw new IllegalStateException("Missing required shared library:" + name);
3438            }
3439            return libraryEntry.apk;
3440        }
3441    }
3442
3443    private @NonNull String getRequiredInstallerLPr() {
3444        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3445        intent.addCategory(Intent.CATEGORY_DEFAULT);
3446        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3447
3448        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3449                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3450                UserHandle.USER_SYSTEM);
3451        if (matches.size() == 1) {
3452            ResolveInfo resolveInfo = matches.get(0);
3453            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3454                throw new RuntimeException("The installer must be a privileged app");
3455            }
3456            return matches.get(0).getComponentInfo().packageName;
3457        } else {
3458            throw new RuntimeException("There must be exactly one installer; found " + matches);
3459        }
3460    }
3461
3462    private @NonNull String getRequiredUninstallerLPr() {
3463        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3464        intent.addCategory(Intent.CATEGORY_DEFAULT);
3465        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3466
3467        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3468                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3469                UserHandle.USER_SYSTEM);
3470        if (resolveInfo == null ||
3471                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3472            throw new RuntimeException("There must be exactly one uninstaller; found "
3473                    + resolveInfo);
3474        }
3475        return resolveInfo.getComponentInfo().packageName;
3476    }
3477
3478    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3479        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3480
3481        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3482                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3483                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3484        ResolveInfo best = null;
3485        final int N = matches.size();
3486        for (int i = 0; i < N; i++) {
3487            final ResolveInfo cur = matches.get(i);
3488            final String packageName = cur.getComponentInfo().packageName;
3489            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3490                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3491                continue;
3492            }
3493
3494            if (best == null || cur.priority > best.priority) {
3495                best = cur;
3496            }
3497        }
3498
3499        if (best != null) {
3500            return best.getComponentInfo().getComponentName();
3501        }
3502        Slog.w(TAG, "Intent filter verifier not found");
3503        return null;
3504    }
3505
3506    @Override
3507    public @Nullable ComponentName getInstantAppResolverComponent() {
3508        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3509            return null;
3510        }
3511        synchronized (mPackages) {
3512            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3513            if (instantAppResolver == null) {
3514                return null;
3515            }
3516            return instantAppResolver.first;
3517        }
3518    }
3519
3520    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3521        final String[] packageArray =
3522                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3523        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3524            if (DEBUG_EPHEMERAL) {
3525                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3526            }
3527            return null;
3528        }
3529
3530        final int callingUid = Binder.getCallingUid();
3531        final int resolveFlags =
3532                MATCH_DIRECT_BOOT_AWARE
3533                | MATCH_DIRECT_BOOT_UNAWARE
3534                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3535        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3536        final Intent resolverIntent = new Intent(actionName);
3537        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3538                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3539        // temporarily look for the old action
3540        if (resolvers.size() == 0) {
3541            if (DEBUG_EPHEMERAL) {
3542                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3543            }
3544            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3545            resolverIntent.setAction(actionName);
3546            resolvers = queryIntentServicesInternal(resolverIntent, null,
3547                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3548        }
3549        final int N = resolvers.size();
3550        if (N == 0) {
3551            if (DEBUG_EPHEMERAL) {
3552                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3553            }
3554            return null;
3555        }
3556
3557        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3558        for (int i = 0; i < N; i++) {
3559            final ResolveInfo info = resolvers.get(i);
3560
3561            if (info.serviceInfo == null) {
3562                continue;
3563            }
3564
3565            final String packageName = info.serviceInfo.packageName;
3566            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3567                if (DEBUG_EPHEMERAL) {
3568                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3569                            + " pkg: " + packageName + ", info:" + info);
3570                }
3571                continue;
3572            }
3573
3574            if (DEBUG_EPHEMERAL) {
3575                Slog.v(TAG, "Ephemeral resolver found;"
3576                        + " pkg: " + packageName + ", info:" + info);
3577            }
3578            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3579        }
3580        if (DEBUG_EPHEMERAL) {
3581            Slog.v(TAG, "Ephemeral resolver NOT found");
3582        }
3583        return null;
3584    }
3585
3586    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3587        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3588        intent.addCategory(Intent.CATEGORY_DEFAULT);
3589        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3590
3591        final int resolveFlags =
3592                MATCH_DIRECT_BOOT_AWARE
3593                | MATCH_DIRECT_BOOT_UNAWARE
3594                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3595        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3596                resolveFlags, UserHandle.USER_SYSTEM);
3597        // temporarily look for the old action
3598        if (matches.isEmpty()) {
3599            if (DEBUG_EPHEMERAL) {
3600                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3601            }
3602            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3603            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3604                    resolveFlags, UserHandle.USER_SYSTEM);
3605        }
3606        Iterator<ResolveInfo> iter = matches.iterator();
3607        while (iter.hasNext()) {
3608            final ResolveInfo rInfo = iter.next();
3609            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3610            if (ps != null) {
3611                final PermissionsState permissionsState = ps.getPermissionsState();
3612                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3613                    continue;
3614                }
3615            }
3616            iter.remove();
3617        }
3618        if (matches.size() == 0) {
3619            return null;
3620        } else if (matches.size() == 1) {
3621            return (ActivityInfo) matches.get(0).getComponentInfo();
3622        } else {
3623            throw new RuntimeException(
3624                    "There must be at most one ephemeral installer; found " + matches);
3625        }
3626    }
3627
3628    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3629            @NonNull ComponentName resolver) {
3630        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3631                .addCategory(Intent.CATEGORY_DEFAULT)
3632                .setPackage(resolver.getPackageName());
3633        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3634        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3635                UserHandle.USER_SYSTEM);
3636        // temporarily look for the old action
3637        if (matches.isEmpty()) {
3638            if (DEBUG_EPHEMERAL) {
3639                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3640            }
3641            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3642            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3643                    UserHandle.USER_SYSTEM);
3644        }
3645        if (matches.isEmpty()) {
3646            return null;
3647        }
3648        return matches.get(0).getComponentInfo().getComponentName();
3649    }
3650
3651    private void primeDomainVerificationsLPw(int userId) {
3652        if (DEBUG_DOMAIN_VERIFICATION) {
3653            Slog.d(TAG, "Priming domain verifications in user " + userId);
3654        }
3655
3656        SystemConfig systemConfig = SystemConfig.getInstance();
3657        ArraySet<String> packages = systemConfig.getLinkedApps();
3658
3659        for (String packageName : packages) {
3660            PackageParser.Package pkg = mPackages.get(packageName);
3661            if (pkg != null) {
3662                if (!pkg.isSystemApp()) {
3663                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3664                    continue;
3665                }
3666
3667                ArraySet<String> domains = null;
3668                for (PackageParser.Activity a : pkg.activities) {
3669                    for (ActivityIntentInfo filter : a.intents) {
3670                        if (hasValidDomains(filter)) {
3671                            if (domains == null) {
3672                                domains = new ArraySet<String>();
3673                            }
3674                            domains.addAll(filter.getHostsList());
3675                        }
3676                    }
3677                }
3678
3679                if (domains != null && domains.size() > 0) {
3680                    if (DEBUG_DOMAIN_VERIFICATION) {
3681                        Slog.v(TAG, "      + " + packageName);
3682                    }
3683                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3684                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3685                    // and then 'always' in the per-user state actually used for intent resolution.
3686                    final IntentFilterVerificationInfo ivi;
3687                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3688                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3689                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3690                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3691                } else {
3692                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3693                            + "' does not handle web links");
3694                }
3695            } else {
3696                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3697            }
3698        }
3699
3700        scheduleWritePackageRestrictionsLocked(userId);
3701        scheduleWriteSettingsLocked();
3702    }
3703
3704    private void applyFactoryDefaultBrowserLPw(int userId) {
3705        // The default browser app's package name is stored in a string resource,
3706        // with a product-specific overlay used for vendor customization.
3707        String browserPkg = mContext.getResources().getString(
3708                com.android.internal.R.string.default_browser);
3709        if (!TextUtils.isEmpty(browserPkg)) {
3710            // non-empty string => required to be a known package
3711            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3712            if (ps == null) {
3713                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3714                browserPkg = null;
3715            } else {
3716                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3717            }
3718        }
3719
3720        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3721        // default.  If there's more than one, just leave everything alone.
3722        if (browserPkg == null) {
3723            calculateDefaultBrowserLPw(userId);
3724        }
3725    }
3726
3727    private void calculateDefaultBrowserLPw(int userId) {
3728        List<String> allBrowsers = resolveAllBrowserApps(userId);
3729        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3730        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3731    }
3732
3733    private List<String> resolveAllBrowserApps(int userId) {
3734        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3735        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3736                PackageManager.MATCH_ALL, userId);
3737
3738        final int count = list.size();
3739        List<String> result = new ArrayList<String>(count);
3740        for (int i=0; i<count; i++) {
3741            ResolveInfo info = list.get(i);
3742            if (info.activityInfo == null
3743                    || !info.handleAllWebDataURI
3744                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3745                    || result.contains(info.activityInfo.packageName)) {
3746                continue;
3747            }
3748            result.add(info.activityInfo.packageName);
3749        }
3750
3751        return result;
3752    }
3753
3754    private boolean packageIsBrowser(String packageName, int userId) {
3755        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3756                PackageManager.MATCH_ALL, userId);
3757        final int N = list.size();
3758        for (int i = 0; i < N; i++) {
3759            ResolveInfo info = list.get(i);
3760            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3761                return true;
3762            }
3763        }
3764        return false;
3765    }
3766
3767    private void checkDefaultBrowser() {
3768        final int myUserId = UserHandle.myUserId();
3769        final String packageName = getDefaultBrowserPackageName(myUserId);
3770        if (packageName != null) {
3771            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3772            if (info == null) {
3773                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3774                synchronized (mPackages) {
3775                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3776                }
3777            }
3778        }
3779    }
3780
3781    @Override
3782    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3783            throws RemoteException {
3784        try {
3785            return super.onTransact(code, data, reply, flags);
3786        } catch (RuntimeException e) {
3787            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3788                Slog.wtf(TAG, "Package Manager Crash", e);
3789            }
3790            throw e;
3791        }
3792    }
3793
3794    static int[] appendInts(int[] cur, int[] add) {
3795        if (add == null) return cur;
3796        if (cur == null) return add;
3797        final int N = add.length;
3798        for (int i=0; i<N; i++) {
3799            cur = appendInt(cur, add[i]);
3800        }
3801        return cur;
3802    }
3803
3804    /**
3805     * Returns whether or not a full application can see an instant application.
3806     * <p>
3807     * Currently, there are three cases in which this can occur:
3808     * <ol>
3809     * <li>The calling application is a "special" process. The special
3810     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3811     *     and {@code 0}</li>
3812     * <li>The calling application has the permission
3813     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3814     * <li>The calling application is the default launcher on the
3815     *     system partition.</li>
3816     * </ol>
3817     */
3818    private boolean canViewInstantApps(int callingUid, int userId) {
3819        if (callingUid == Process.SYSTEM_UID
3820                || callingUid == Process.SHELL_UID
3821                || callingUid == Process.ROOT_UID) {
3822            return true;
3823        }
3824        if (mContext.checkCallingOrSelfPermission(
3825                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3826            return true;
3827        }
3828        if (mContext.checkCallingOrSelfPermission(
3829                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3830            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3831            if (homeComponent != null
3832                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3833                return true;
3834            }
3835        }
3836        return false;
3837    }
3838
3839    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3840        if (!sUserManager.exists(userId)) return null;
3841        if (ps == null) {
3842            return null;
3843        }
3844        PackageParser.Package p = ps.pkg;
3845        if (p == null) {
3846            return null;
3847        }
3848        final int callingUid = Binder.getCallingUid();
3849        // Filter out ephemeral app metadata:
3850        //   * The system/shell/root can see metadata for any app
3851        //   * An installed app can see metadata for 1) other installed apps
3852        //     and 2) ephemeral apps that have explicitly interacted with it
3853        //   * Ephemeral apps can only see their own data and exposed installed apps
3854        //   * Holding a signature permission allows seeing instant apps
3855        if (filterAppAccessLPr(ps, callingUid, userId)) {
3856            return null;
3857        }
3858
3859        final PermissionsState permissionsState = ps.getPermissionsState();
3860
3861        // Compute GIDs only if requested
3862        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3863                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3864        // Compute granted permissions only if package has requested permissions
3865        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3866                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3867        final PackageUserState state = ps.readUserState(userId);
3868
3869        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3870                && ps.isSystem()) {
3871            flags |= MATCH_ANY_USER;
3872        }
3873
3874        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3875                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3876
3877        if (packageInfo == null) {
3878            return null;
3879        }
3880
3881        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3882                resolveExternalPackageNameLPr(p);
3883
3884        return packageInfo;
3885    }
3886
3887    @Override
3888    public void checkPackageStartable(String packageName, int userId) {
3889        final int callingUid = Binder.getCallingUid();
3890        if (getInstantAppPackageName(callingUid) != null) {
3891            throw new SecurityException("Instant applications don't have access to this method");
3892        }
3893        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3894        synchronized (mPackages) {
3895            final PackageSetting ps = mSettings.mPackages.get(packageName);
3896            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3897                throw new SecurityException("Package " + packageName + " was not found!");
3898            }
3899
3900            if (!ps.getInstalled(userId)) {
3901                throw new SecurityException(
3902                        "Package " + packageName + " was not installed for user " + userId + "!");
3903            }
3904
3905            if (mSafeMode && !ps.isSystem()) {
3906                throw new SecurityException("Package " + packageName + " not a system app!");
3907            }
3908
3909            if (mFrozenPackages.contains(packageName)) {
3910                throw new SecurityException("Package " + packageName + " is currently frozen!");
3911            }
3912
3913            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3914                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3915            }
3916        }
3917    }
3918
3919    @Override
3920    public boolean isPackageAvailable(String packageName, int userId) {
3921        if (!sUserManager.exists(userId)) return false;
3922        final int callingUid = Binder.getCallingUid();
3923        enforceCrossUserPermission(callingUid, userId,
3924                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3925        synchronized (mPackages) {
3926            PackageParser.Package p = mPackages.get(packageName);
3927            if (p != null) {
3928                final PackageSetting ps = (PackageSetting) p.mExtras;
3929                if (filterAppAccessLPr(ps, callingUid, userId)) {
3930                    return false;
3931                }
3932                if (ps != null) {
3933                    final PackageUserState state = ps.readUserState(userId);
3934                    if (state != null) {
3935                        return PackageParser.isAvailable(state);
3936                    }
3937                }
3938            }
3939        }
3940        return false;
3941    }
3942
3943    @Override
3944    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3945        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3946                flags, Binder.getCallingUid(), userId);
3947    }
3948
3949    @Override
3950    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3951            int flags, int userId) {
3952        return getPackageInfoInternal(versionedPackage.getPackageName(),
3953                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3954    }
3955
3956    /**
3957     * Important: The provided filterCallingUid is used exclusively to filter out packages
3958     * that can be seen based on user state. It's typically the original caller uid prior
3959     * to clearing. Because it can only be provided by trusted code, it's value can be
3960     * trusted and will be used as-is; unlike userId which will be validated by this method.
3961     */
3962    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3963            int flags, int filterCallingUid, int userId) {
3964        if (!sUserManager.exists(userId)) return null;
3965        flags = updateFlagsForPackage(flags, userId, packageName);
3966        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3967                false /* requireFullPermission */, false /* checkShell */, "get package info");
3968
3969        // reader
3970        synchronized (mPackages) {
3971            // Normalize package name to handle renamed packages and static libs
3972            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3973
3974            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3975            if (matchFactoryOnly) {
3976                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3977                if (ps != null) {
3978                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3979                        return null;
3980                    }
3981                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3982                        return null;
3983                    }
3984                    return generatePackageInfo(ps, flags, userId);
3985                }
3986            }
3987
3988            PackageParser.Package p = mPackages.get(packageName);
3989            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3990                return null;
3991            }
3992            if (DEBUG_PACKAGE_INFO)
3993                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3994            if (p != null) {
3995                final PackageSetting ps = (PackageSetting) p.mExtras;
3996                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3997                    return null;
3998                }
3999                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4000                    return null;
4001                }
4002                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4003            }
4004            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4005                final PackageSetting ps = mSettings.mPackages.get(packageName);
4006                if (ps == null) return null;
4007                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4008                    return null;
4009                }
4010                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4011                    return null;
4012                }
4013                return generatePackageInfo(ps, flags, userId);
4014            }
4015        }
4016        return null;
4017    }
4018
4019    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4020        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4021            return true;
4022        }
4023        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4024            return true;
4025        }
4026        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4027            return true;
4028        }
4029        return false;
4030    }
4031
4032    private boolean isComponentVisibleToInstantApp(
4033            @Nullable ComponentName component, @ComponentType int type) {
4034        if (type == TYPE_ACTIVITY) {
4035            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4036            return activity != null
4037                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4038                    : false;
4039        } else if (type == TYPE_RECEIVER) {
4040            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4041            return activity != null
4042                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4043                    : false;
4044        } else if (type == TYPE_SERVICE) {
4045            final PackageParser.Service service = mServices.mServices.get(component);
4046            return service != null
4047                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4048                    : false;
4049        } else if (type == TYPE_PROVIDER) {
4050            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4051            return provider != null
4052                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4053                    : false;
4054        } else if (type == TYPE_UNKNOWN) {
4055            return isComponentVisibleToInstantApp(component);
4056        }
4057        return false;
4058    }
4059
4060    /**
4061     * Returns whether or not access to the application should be filtered.
4062     * <p>
4063     * Access may be limited based upon whether the calling or target applications
4064     * are instant applications.
4065     *
4066     * @see #canAccessInstantApps(int)
4067     */
4068    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4069            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4070        // if we're in an isolated process, get the real calling UID
4071        if (Process.isIsolated(callingUid)) {
4072            callingUid = mIsolatedOwners.get(callingUid);
4073        }
4074        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4075        final boolean callerIsInstantApp = instantAppPkgName != null;
4076        if (ps == null) {
4077            if (callerIsInstantApp) {
4078                // pretend the application exists, but, needs to be filtered
4079                return true;
4080            }
4081            return false;
4082        }
4083        // if the target and caller are the same application, don't filter
4084        if (isCallerSameApp(ps.name, callingUid)) {
4085            return false;
4086        }
4087        if (callerIsInstantApp) {
4088            // request for a specific component; if it hasn't been explicitly exposed, filter
4089            if (component != null) {
4090                return !isComponentVisibleToInstantApp(component, componentType);
4091            }
4092            // request for application; if no components have been explicitly exposed, filter
4093            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4094        }
4095        if (ps.getInstantApp(userId)) {
4096            // caller can see all components of all instant applications, don't filter
4097            if (canViewInstantApps(callingUid, userId)) {
4098                return false;
4099            }
4100            // request for a specific instant application component, filter
4101            if (component != null) {
4102                return true;
4103            }
4104            // request for an instant application; if the caller hasn't been granted access, filter
4105            return !mInstantAppRegistry.isInstantAccessGranted(
4106                    userId, UserHandle.getAppId(callingUid), ps.appId);
4107        }
4108        return false;
4109    }
4110
4111    /**
4112     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4113     */
4114    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4115        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4116    }
4117
4118    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4119            int flags) {
4120        // Callers can access only the libs they depend on, otherwise they need to explicitly
4121        // ask for the shared libraries given the caller is allowed to access all static libs.
4122        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4123            // System/shell/root get to see all static libs
4124            final int appId = UserHandle.getAppId(uid);
4125            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4126                    || appId == Process.ROOT_UID) {
4127                return false;
4128            }
4129        }
4130
4131        // No package means no static lib as it is always on internal storage
4132        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4133            return false;
4134        }
4135
4136        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4137                ps.pkg.staticSharedLibVersion);
4138        if (libEntry == null) {
4139            return false;
4140        }
4141
4142        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4143        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4144        if (uidPackageNames == null) {
4145            return true;
4146        }
4147
4148        for (String uidPackageName : uidPackageNames) {
4149            if (ps.name.equals(uidPackageName)) {
4150                return false;
4151            }
4152            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4153            if (uidPs != null) {
4154                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4155                        libEntry.info.getName());
4156                if (index < 0) {
4157                    continue;
4158                }
4159                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4160                    return false;
4161                }
4162            }
4163        }
4164        return true;
4165    }
4166
4167    @Override
4168    public String[] currentToCanonicalPackageNames(String[] names) {
4169        final int callingUid = Binder.getCallingUid();
4170        if (getInstantAppPackageName(callingUid) != null) {
4171            return names;
4172        }
4173        final String[] out = new String[names.length];
4174        // reader
4175        synchronized (mPackages) {
4176            final int callingUserId = UserHandle.getUserId(callingUid);
4177            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4178            for (int i=names.length-1; i>=0; i--) {
4179                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4180                boolean translateName = false;
4181                if (ps != null && ps.realName != null) {
4182                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4183                    translateName = !targetIsInstantApp
4184                            || canViewInstantApps
4185                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4186                                    UserHandle.getAppId(callingUid), ps.appId);
4187                }
4188                out[i] = translateName ? ps.realName : names[i];
4189            }
4190        }
4191        return out;
4192    }
4193
4194    @Override
4195    public String[] canonicalToCurrentPackageNames(String[] names) {
4196        final int callingUid = Binder.getCallingUid();
4197        if (getInstantAppPackageName(callingUid) != null) {
4198            return names;
4199        }
4200        final String[] out = new String[names.length];
4201        // reader
4202        synchronized (mPackages) {
4203            final int callingUserId = UserHandle.getUserId(callingUid);
4204            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4205            for (int i=names.length-1; i>=0; i--) {
4206                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4207                boolean translateName = false;
4208                if (cur != null) {
4209                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4210                    final boolean targetIsInstantApp =
4211                            ps != null && ps.getInstantApp(callingUserId);
4212                    translateName = !targetIsInstantApp
4213                            || canViewInstantApps
4214                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4215                                    UserHandle.getAppId(callingUid), ps.appId);
4216                }
4217                out[i] = translateName ? cur : names[i];
4218            }
4219        }
4220        return out;
4221    }
4222
4223    @Override
4224    public int getPackageUid(String packageName, int flags, int userId) {
4225        if (!sUserManager.exists(userId)) return -1;
4226        final int callingUid = Binder.getCallingUid();
4227        flags = updateFlagsForPackage(flags, userId, packageName);
4228        enforceCrossUserPermission(callingUid, userId,
4229                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4230
4231        // reader
4232        synchronized (mPackages) {
4233            final PackageParser.Package p = mPackages.get(packageName);
4234            if (p != null && p.isMatch(flags)) {
4235                PackageSetting ps = (PackageSetting) p.mExtras;
4236                if (filterAppAccessLPr(ps, callingUid, userId)) {
4237                    return -1;
4238                }
4239                return UserHandle.getUid(userId, p.applicationInfo.uid);
4240            }
4241            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4242                final PackageSetting ps = mSettings.mPackages.get(packageName);
4243                if (ps != null && ps.isMatch(flags)
4244                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4245                    return UserHandle.getUid(userId, ps.appId);
4246                }
4247            }
4248        }
4249
4250        return -1;
4251    }
4252
4253    @Override
4254    public int[] getPackageGids(String packageName, int flags, int userId) {
4255        if (!sUserManager.exists(userId)) return null;
4256        final int callingUid = Binder.getCallingUid();
4257        flags = updateFlagsForPackage(flags, userId, packageName);
4258        enforceCrossUserPermission(callingUid, userId,
4259                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4260
4261        // reader
4262        synchronized (mPackages) {
4263            final PackageParser.Package p = mPackages.get(packageName);
4264            if (p != null && p.isMatch(flags)) {
4265                PackageSetting ps = (PackageSetting) p.mExtras;
4266                if (filterAppAccessLPr(ps, callingUid, userId)) {
4267                    return null;
4268                }
4269                // TODO: Shouldn't this be checking for package installed state for userId and
4270                // return null?
4271                return ps.getPermissionsState().computeGids(userId);
4272            }
4273            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4274                final PackageSetting ps = mSettings.mPackages.get(packageName);
4275                if (ps != null && ps.isMatch(flags)
4276                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4277                    return ps.getPermissionsState().computeGids(userId);
4278                }
4279            }
4280        }
4281
4282        return null;
4283    }
4284
4285    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4286        if (bp.perm != null) {
4287            return PackageParser.generatePermissionInfo(bp.perm, flags);
4288        }
4289        PermissionInfo pi = new PermissionInfo();
4290        pi.name = bp.name;
4291        pi.packageName = bp.sourcePackage;
4292        pi.nonLocalizedLabel = bp.name;
4293        pi.protectionLevel = bp.protectionLevel;
4294        return pi;
4295    }
4296
4297    @Override
4298    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4299        final int callingUid = Binder.getCallingUid();
4300        if (getInstantAppPackageName(callingUid) != null) {
4301            return null;
4302        }
4303        // reader
4304        synchronized (mPackages) {
4305            final BasePermission p = mSettings.mPermissions.get(name);
4306            if (p == null) {
4307                return null;
4308            }
4309            // If the caller is an app that targets pre 26 SDK drop protection flags.
4310            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4311            if (permissionInfo != null) {
4312                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4313                        permissionInfo.protectionLevel, packageName, callingUid);
4314                if (permissionInfo.protectionLevel != protectionLevel) {
4315                    // If we return different protection level, don't use the cached info
4316                    if (p.perm != null && p.perm.info == permissionInfo) {
4317                        permissionInfo = new PermissionInfo(permissionInfo);
4318                    }
4319                    permissionInfo.protectionLevel = protectionLevel;
4320                }
4321            }
4322            return permissionInfo;
4323        }
4324    }
4325
4326    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4327            String packageName, int uid) {
4328        // Signature permission flags area always reported
4329        final int protectionLevelMasked = protectionLevel
4330                & (PermissionInfo.PROTECTION_NORMAL
4331                | PermissionInfo.PROTECTION_DANGEROUS
4332                | PermissionInfo.PROTECTION_SIGNATURE);
4333        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4334            return protectionLevel;
4335        }
4336
4337        // System sees all flags.
4338        final int appId = UserHandle.getAppId(uid);
4339        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4340                || appId == Process.SHELL_UID) {
4341            return protectionLevel;
4342        }
4343
4344        // Normalize package name to handle renamed packages and static libs
4345        packageName = resolveInternalPackageNameLPr(packageName,
4346                PackageManager.VERSION_CODE_HIGHEST);
4347
4348        // Apps that target O see flags for all protection levels.
4349        final PackageSetting ps = mSettings.mPackages.get(packageName);
4350        if (ps == null) {
4351            return protectionLevel;
4352        }
4353        if (ps.appId != appId) {
4354            return protectionLevel;
4355        }
4356
4357        final PackageParser.Package pkg = mPackages.get(packageName);
4358        if (pkg == null) {
4359            return protectionLevel;
4360        }
4361        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4362            return protectionLevelMasked;
4363        }
4364
4365        return protectionLevel;
4366    }
4367
4368    @Override
4369    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4370            int flags) {
4371        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4372            return null;
4373        }
4374        // reader
4375        synchronized (mPackages) {
4376            if (group != null && !mPermissionGroups.containsKey(group)) {
4377                // This is thrown as NameNotFoundException
4378                return null;
4379            }
4380
4381            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4382            for (BasePermission p : mSettings.mPermissions.values()) {
4383                if (group == null) {
4384                    if (p.perm == null || p.perm.info.group == null) {
4385                        out.add(generatePermissionInfo(p, flags));
4386                    }
4387                } else {
4388                    if (p.perm != null && group.equals(p.perm.info.group)) {
4389                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4390                    }
4391                }
4392            }
4393            return new ParceledListSlice<>(out);
4394        }
4395    }
4396
4397    @Override
4398    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4399        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4400            return null;
4401        }
4402        // reader
4403        synchronized (mPackages) {
4404            return PackageParser.generatePermissionGroupInfo(
4405                    mPermissionGroups.get(name), flags);
4406        }
4407    }
4408
4409    @Override
4410    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4411        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4412            return ParceledListSlice.emptyList();
4413        }
4414        // reader
4415        synchronized (mPackages) {
4416            final int N = mPermissionGroups.size();
4417            ArrayList<PermissionGroupInfo> out
4418                    = new ArrayList<PermissionGroupInfo>(N);
4419            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4420                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4421            }
4422            return new ParceledListSlice<>(out);
4423        }
4424    }
4425
4426    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4427            int filterCallingUid, int userId) {
4428        if (!sUserManager.exists(userId)) return null;
4429        PackageSetting ps = mSettings.mPackages.get(packageName);
4430        if (ps != null) {
4431            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4432                return null;
4433            }
4434            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4435                return null;
4436            }
4437            if (ps.pkg == null) {
4438                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4439                if (pInfo != null) {
4440                    return pInfo.applicationInfo;
4441                }
4442                return null;
4443            }
4444            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4445                    ps.readUserState(userId), userId);
4446            if (ai != null) {
4447                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4448            }
4449            return ai;
4450        }
4451        return null;
4452    }
4453
4454    @Override
4455    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4456        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4457    }
4458
4459    /**
4460     * Important: The provided filterCallingUid is used exclusively to filter out applications
4461     * that can be seen based on user state. It's typically the original caller uid prior
4462     * to clearing. Because it can only be provided by trusted code, it's value can be
4463     * trusted and will be used as-is; unlike userId which will be validated by this method.
4464     */
4465    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4466            int filterCallingUid, int userId) {
4467        if (!sUserManager.exists(userId)) return null;
4468        flags = updateFlagsForApplication(flags, userId, packageName);
4469        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4470                false /* requireFullPermission */, false /* checkShell */, "get application info");
4471
4472        // writer
4473        synchronized (mPackages) {
4474            // Normalize package name to handle renamed packages and static libs
4475            packageName = resolveInternalPackageNameLPr(packageName,
4476                    PackageManager.VERSION_CODE_HIGHEST);
4477
4478            PackageParser.Package p = mPackages.get(packageName);
4479            if (DEBUG_PACKAGE_INFO) Log.v(
4480                    TAG, "getApplicationInfo " + packageName
4481                    + ": " + p);
4482            if (p != null) {
4483                PackageSetting ps = mSettings.mPackages.get(packageName);
4484                if (ps == null) return null;
4485                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4486                    return null;
4487                }
4488                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4489                    return null;
4490                }
4491                // Note: isEnabledLP() does not apply here - always return info
4492                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4493                        p, flags, ps.readUserState(userId), userId);
4494                if (ai != null) {
4495                    ai.packageName = resolveExternalPackageNameLPr(p);
4496                }
4497                return ai;
4498            }
4499            if ("android".equals(packageName)||"system".equals(packageName)) {
4500                return mAndroidApplication;
4501            }
4502            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4503                // Already generates the external package name
4504                return generateApplicationInfoFromSettingsLPw(packageName,
4505                        flags, filterCallingUid, userId);
4506            }
4507        }
4508        return null;
4509    }
4510
4511    private String normalizePackageNameLPr(String packageName) {
4512        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4513        return normalizedPackageName != null ? normalizedPackageName : packageName;
4514    }
4515
4516    @Override
4517    public void deletePreloadsFileCache() {
4518        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4519            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4520        }
4521        File dir = Environment.getDataPreloadsFileCacheDirectory();
4522        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4523        FileUtils.deleteContents(dir);
4524    }
4525
4526    @Override
4527    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4528            final int storageFlags, final IPackageDataObserver observer) {
4529        mContext.enforceCallingOrSelfPermission(
4530                android.Manifest.permission.CLEAR_APP_CACHE, null);
4531        mHandler.post(() -> {
4532            boolean success = false;
4533            try {
4534                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4535                success = true;
4536            } catch (IOException e) {
4537                Slog.w(TAG, e);
4538            }
4539            if (observer != null) {
4540                try {
4541                    observer.onRemoveCompleted(null, success);
4542                } catch (RemoteException e) {
4543                    Slog.w(TAG, e);
4544                }
4545            }
4546        });
4547    }
4548
4549    @Override
4550    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4551            final int storageFlags, final IntentSender pi) {
4552        mContext.enforceCallingOrSelfPermission(
4553                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4554        mHandler.post(() -> {
4555            boolean success = false;
4556            try {
4557                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4558                success = true;
4559            } catch (IOException e) {
4560                Slog.w(TAG, e);
4561            }
4562            if (pi != null) {
4563                try {
4564                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4565                } catch (SendIntentException e) {
4566                    Slog.w(TAG, e);
4567                }
4568            }
4569        });
4570    }
4571
4572    /**
4573     * Blocking call to clear various types of cached data across the system
4574     * until the requested bytes are available.
4575     */
4576    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4577        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4578        final File file = storage.findPathForUuid(volumeUuid);
4579        if (file.getUsableSpace() >= bytes) return;
4580
4581        if (ENABLE_FREE_CACHE_V2) {
4582            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4583                    volumeUuid);
4584            final boolean aggressive = (storageFlags
4585                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4586            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4587
4588            // 1. Pre-flight to determine if we have any chance to succeed
4589            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4590            if (internalVolume && (aggressive || SystemProperties
4591                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4592                deletePreloadsFileCache();
4593                if (file.getUsableSpace() >= bytes) return;
4594            }
4595
4596            // 3. Consider parsed APK data (aggressive only)
4597            if (internalVolume && aggressive) {
4598                FileUtils.deleteContents(mCacheDir);
4599                if (file.getUsableSpace() >= bytes) return;
4600            }
4601
4602            // 4. Consider cached app data (above quotas)
4603            try {
4604                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4605                        Installer.FLAG_FREE_CACHE_V2);
4606            } catch (InstallerException ignored) {
4607            }
4608            if (file.getUsableSpace() >= bytes) return;
4609
4610            // 5. Consider shared libraries with refcount=0 and age>min cache period
4611            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4612                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4613                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4614                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4615                return;
4616            }
4617
4618            // 6. Consider dexopt output (aggressive only)
4619            // TODO: Implement
4620
4621            // 7. Consider installed instant apps unused longer than min cache period
4622            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4623                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4624                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4625                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4626                return;
4627            }
4628
4629            // 8. Consider cached app data (below quotas)
4630            try {
4631                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4632                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4633            } catch (InstallerException ignored) {
4634            }
4635            if (file.getUsableSpace() >= bytes) return;
4636
4637            // 9. Consider DropBox entries
4638            // TODO: Implement
4639
4640            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4641            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4642                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4643                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4644                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4645                return;
4646            }
4647        } else {
4648            try {
4649                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4650            } catch (InstallerException ignored) {
4651            }
4652            if (file.getUsableSpace() >= bytes) return;
4653        }
4654
4655        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4656    }
4657
4658    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4659            throws IOException {
4660        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4661        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4662
4663        List<VersionedPackage> packagesToDelete = null;
4664        final long now = System.currentTimeMillis();
4665
4666        synchronized (mPackages) {
4667            final int[] allUsers = sUserManager.getUserIds();
4668            final int libCount = mSharedLibraries.size();
4669            for (int i = 0; i < libCount; i++) {
4670                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4671                if (versionedLib == null) {
4672                    continue;
4673                }
4674                final int versionCount = versionedLib.size();
4675                for (int j = 0; j < versionCount; j++) {
4676                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4677                    // Skip packages that are not static shared libs.
4678                    if (!libInfo.isStatic()) {
4679                        break;
4680                    }
4681                    // Important: We skip static shared libs used for some user since
4682                    // in such a case we need to keep the APK on the device. The check for
4683                    // a lib being used for any user is performed by the uninstall call.
4684                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4685                    // Resolve the package name - we use synthetic package names internally
4686                    final String internalPackageName = resolveInternalPackageNameLPr(
4687                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4688                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4689                    // Skip unused static shared libs cached less than the min period
4690                    // to prevent pruning a lib needed by a subsequently installed package.
4691                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4692                        continue;
4693                    }
4694                    if (packagesToDelete == null) {
4695                        packagesToDelete = new ArrayList<>();
4696                    }
4697                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4698                            declaringPackage.getVersionCode()));
4699                }
4700            }
4701        }
4702
4703        if (packagesToDelete != null) {
4704            final int packageCount = packagesToDelete.size();
4705            for (int i = 0; i < packageCount; i++) {
4706                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4707                // Delete the package synchronously (will fail of the lib used for any user).
4708                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4709                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4710                                == PackageManager.DELETE_SUCCEEDED) {
4711                    if (volume.getUsableSpace() >= neededSpace) {
4712                        return true;
4713                    }
4714                }
4715            }
4716        }
4717
4718        return false;
4719    }
4720
4721    /**
4722     * Update given flags based on encryption status of current user.
4723     */
4724    private int updateFlags(int flags, int userId) {
4725        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4726                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4727            // Caller expressed an explicit opinion about what encryption
4728            // aware/unaware components they want to see, so fall through and
4729            // give them what they want
4730        } else {
4731            // Caller expressed no opinion, so match based on user state
4732            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4733                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4734            } else {
4735                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4736            }
4737        }
4738        return flags;
4739    }
4740
4741    private UserManagerInternal getUserManagerInternal() {
4742        if (mUserManagerInternal == null) {
4743            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4744        }
4745        return mUserManagerInternal;
4746    }
4747
4748    private DeviceIdleController.LocalService getDeviceIdleController() {
4749        if (mDeviceIdleController == null) {
4750            mDeviceIdleController =
4751                    LocalServices.getService(DeviceIdleController.LocalService.class);
4752        }
4753        return mDeviceIdleController;
4754    }
4755
4756    /**
4757     * Update given flags when being used to request {@link PackageInfo}.
4758     */
4759    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4760        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4761        boolean triaged = true;
4762        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4763                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4764            // Caller is asking for component details, so they'd better be
4765            // asking for specific encryption matching behavior, or be triaged
4766            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4767                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4768                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4769                triaged = false;
4770            }
4771        }
4772        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4773                | PackageManager.MATCH_SYSTEM_ONLY
4774                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4775            triaged = false;
4776        }
4777        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4778            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4779                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4780                    + Debug.getCallers(5));
4781        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4782                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4783            // If the caller wants all packages and has a restricted profile associated with it,
4784            // then match all users. This is to make sure that launchers that need to access work
4785            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4786            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4787            flags |= PackageManager.MATCH_ANY_USER;
4788        }
4789        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4790            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4791                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4792        }
4793        return updateFlags(flags, userId);
4794    }
4795
4796    /**
4797     * Update given flags when being used to request {@link ApplicationInfo}.
4798     */
4799    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4800        return updateFlagsForPackage(flags, userId, cookie);
4801    }
4802
4803    /**
4804     * Update given flags when being used to request {@link ComponentInfo}.
4805     */
4806    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4807        if (cookie instanceof Intent) {
4808            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4809                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4810            }
4811        }
4812
4813        boolean triaged = true;
4814        // Caller is asking for component details, so they'd better be
4815        // asking for specific encryption matching behavior, or be triaged
4816        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4817                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4818                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4819            triaged = false;
4820        }
4821        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4822            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4823                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4824        }
4825
4826        return updateFlags(flags, userId);
4827    }
4828
4829    /**
4830     * Update given intent when being used to request {@link ResolveInfo}.
4831     */
4832    private Intent updateIntentForResolve(Intent intent) {
4833        if (intent.getSelector() != null) {
4834            intent = intent.getSelector();
4835        }
4836        if (DEBUG_PREFERRED) {
4837            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4838        }
4839        return intent;
4840    }
4841
4842    /**
4843     * Update given flags when being used to request {@link ResolveInfo}.
4844     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4845     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4846     * flag set. However, this flag is only honoured in three circumstances:
4847     * <ul>
4848     * <li>when called from a system process</li>
4849     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4850     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4851     * action and a {@code android.intent.category.BROWSABLE} category</li>
4852     * </ul>
4853     */
4854    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4855        return updateFlagsForResolve(flags, userId, intent, callingUid,
4856                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4857    }
4858    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4859            boolean wantInstantApps) {
4860        return updateFlagsForResolve(flags, userId, intent, callingUid,
4861                wantInstantApps, false /*onlyExposedExplicitly*/);
4862    }
4863    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4864            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4865        // Safe mode means we shouldn't match any third-party components
4866        if (mSafeMode) {
4867            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4868        }
4869        if (getInstantAppPackageName(callingUid) != null) {
4870            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4871            if (onlyExposedExplicitly) {
4872                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4873            }
4874            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4875            flags |= PackageManager.MATCH_INSTANT;
4876        } else {
4877            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4878            final boolean allowMatchInstant =
4879                    (wantInstantApps
4880                            && Intent.ACTION_VIEW.equals(intent.getAction())
4881                            && hasWebURI(intent))
4882                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4883            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4884                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4885            if (!allowMatchInstant) {
4886                flags &= ~PackageManager.MATCH_INSTANT;
4887            }
4888        }
4889        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4890    }
4891
4892    @Override
4893    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4894        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4895    }
4896
4897    /**
4898     * Important: The provided filterCallingUid is used exclusively to filter out activities
4899     * that can be seen based on user state. It's typically the original caller uid prior
4900     * to clearing. Because it can only be provided by trusted code, it's value can be
4901     * trusted and will be used as-is; unlike userId which will be validated by this method.
4902     */
4903    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4904            int filterCallingUid, int userId) {
4905        if (!sUserManager.exists(userId)) return null;
4906        flags = updateFlagsForComponent(flags, userId, component);
4907        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4908                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4909        synchronized (mPackages) {
4910            PackageParser.Activity a = mActivities.mActivities.get(component);
4911
4912            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4913            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4914                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4915                if (ps == null) return null;
4916                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4917                    return null;
4918                }
4919                return PackageParser.generateActivityInfo(
4920                        a, flags, ps.readUserState(userId), userId);
4921            }
4922            if (mResolveComponentName.equals(component)) {
4923                return PackageParser.generateActivityInfo(
4924                        mResolveActivity, flags, new PackageUserState(), userId);
4925            }
4926        }
4927        return null;
4928    }
4929
4930    @Override
4931    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4932            String resolvedType) {
4933        synchronized (mPackages) {
4934            if (component.equals(mResolveComponentName)) {
4935                // The resolver supports EVERYTHING!
4936                return true;
4937            }
4938            final int callingUid = Binder.getCallingUid();
4939            final int callingUserId = UserHandle.getUserId(callingUid);
4940            PackageParser.Activity a = mActivities.mActivities.get(component);
4941            if (a == null) {
4942                return false;
4943            }
4944            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4945            if (ps == null) {
4946                return false;
4947            }
4948            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4949                return false;
4950            }
4951            for (int i=0; i<a.intents.size(); i++) {
4952                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4953                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4954                    return true;
4955                }
4956            }
4957            return false;
4958        }
4959    }
4960
4961    @Override
4962    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4963        if (!sUserManager.exists(userId)) return null;
4964        final int callingUid = Binder.getCallingUid();
4965        flags = updateFlagsForComponent(flags, userId, component);
4966        enforceCrossUserPermission(callingUid, userId,
4967                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4968        synchronized (mPackages) {
4969            PackageParser.Activity a = mReceivers.mActivities.get(component);
4970            if (DEBUG_PACKAGE_INFO) Log.v(
4971                TAG, "getReceiverInfo " + component + ": " + a);
4972            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4973                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4974                if (ps == null) return null;
4975                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4976                    return null;
4977                }
4978                return PackageParser.generateActivityInfo(
4979                        a, flags, ps.readUserState(userId), userId);
4980            }
4981        }
4982        return null;
4983    }
4984
4985    @Override
4986    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4987            int flags, int userId) {
4988        if (!sUserManager.exists(userId)) return null;
4989        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4990        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4991            return null;
4992        }
4993
4994        flags = updateFlagsForPackage(flags, userId, null);
4995
4996        final boolean canSeeStaticLibraries =
4997                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4998                        == PERMISSION_GRANTED
4999                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5000                        == PERMISSION_GRANTED
5001                || canRequestPackageInstallsInternal(packageName,
5002                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5003                        false  /* throwIfPermNotDeclared*/)
5004                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5005                        == PERMISSION_GRANTED;
5006
5007        synchronized (mPackages) {
5008            List<SharedLibraryInfo> result = null;
5009
5010            final int libCount = mSharedLibraries.size();
5011            for (int i = 0; i < libCount; i++) {
5012                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5013                if (versionedLib == null) {
5014                    continue;
5015                }
5016
5017                final int versionCount = versionedLib.size();
5018                for (int j = 0; j < versionCount; j++) {
5019                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5020                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5021                        break;
5022                    }
5023                    final long identity = Binder.clearCallingIdentity();
5024                    try {
5025                        PackageInfo packageInfo = getPackageInfoVersioned(
5026                                libInfo.getDeclaringPackage(), flags
5027                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5028                        if (packageInfo == null) {
5029                            continue;
5030                        }
5031                    } finally {
5032                        Binder.restoreCallingIdentity(identity);
5033                    }
5034
5035                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5036                            libInfo.getVersion(), libInfo.getType(),
5037                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5038                            flags, userId));
5039
5040                    if (result == null) {
5041                        result = new ArrayList<>();
5042                    }
5043                    result.add(resLibInfo);
5044                }
5045            }
5046
5047            return result != null ? new ParceledListSlice<>(result) : null;
5048        }
5049    }
5050
5051    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5052            SharedLibraryInfo libInfo, int flags, int userId) {
5053        List<VersionedPackage> versionedPackages = null;
5054        final int packageCount = mSettings.mPackages.size();
5055        for (int i = 0; i < packageCount; i++) {
5056            PackageSetting ps = mSettings.mPackages.valueAt(i);
5057
5058            if (ps == null) {
5059                continue;
5060            }
5061
5062            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5063                continue;
5064            }
5065
5066            final String libName = libInfo.getName();
5067            if (libInfo.isStatic()) {
5068                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5069                if (libIdx < 0) {
5070                    continue;
5071                }
5072                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5073                    continue;
5074                }
5075                if (versionedPackages == null) {
5076                    versionedPackages = new ArrayList<>();
5077                }
5078                // If the dependent is a static shared lib, use the public package name
5079                String dependentPackageName = ps.name;
5080                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5081                    dependentPackageName = ps.pkg.manifestPackageName;
5082                }
5083                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5084            } else if (ps.pkg != null) {
5085                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5086                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5087                    if (versionedPackages == null) {
5088                        versionedPackages = new ArrayList<>();
5089                    }
5090                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5091                }
5092            }
5093        }
5094
5095        return versionedPackages;
5096    }
5097
5098    @Override
5099    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5100        if (!sUserManager.exists(userId)) return null;
5101        final int callingUid = Binder.getCallingUid();
5102        flags = updateFlagsForComponent(flags, userId, component);
5103        enforceCrossUserPermission(callingUid, userId,
5104                false /* requireFullPermission */, false /* checkShell */, "get service info");
5105        synchronized (mPackages) {
5106            PackageParser.Service s = mServices.mServices.get(component);
5107            if (DEBUG_PACKAGE_INFO) Log.v(
5108                TAG, "getServiceInfo " + component + ": " + s);
5109            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5110                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5111                if (ps == null) return null;
5112                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5113                    return null;
5114                }
5115                return PackageParser.generateServiceInfo(
5116                        s, flags, ps.readUserState(userId), userId);
5117            }
5118        }
5119        return null;
5120    }
5121
5122    @Override
5123    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5124        if (!sUserManager.exists(userId)) return null;
5125        final int callingUid = Binder.getCallingUid();
5126        flags = updateFlagsForComponent(flags, userId, component);
5127        enforceCrossUserPermission(callingUid, userId,
5128                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5129        synchronized (mPackages) {
5130            PackageParser.Provider p = mProviders.mProviders.get(component);
5131            if (DEBUG_PACKAGE_INFO) Log.v(
5132                TAG, "getProviderInfo " + component + ": " + p);
5133            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5134                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5135                if (ps == null) return null;
5136                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5137                    return null;
5138                }
5139                return PackageParser.generateProviderInfo(
5140                        p, flags, ps.readUserState(userId), userId);
5141            }
5142        }
5143        return null;
5144    }
5145
5146    @Override
5147    public String[] getSystemSharedLibraryNames() {
5148        // allow instant applications
5149        synchronized (mPackages) {
5150            Set<String> libs = null;
5151            final int libCount = mSharedLibraries.size();
5152            for (int i = 0; i < libCount; i++) {
5153                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5154                if (versionedLib == null) {
5155                    continue;
5156                }
5157                final int versionCount = versionedLib.size();
5158                for (int j = 0; j < versionCount; j++) {
5159                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5160                    if (!libEntry.info.isStatic()) {
5161                        if (libs == null) {
5162                            libs = new ArraySet<>();
5163                        }
5164                        libs.add(libEntry.info.getName());
5165                        break;
5166                    }
5167                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5168                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5169                            UserHandle.getUserId(Binder.getCallingUid()),
5170                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5171                        if (libs == null) {
5172                            libs = new ArraySet<>();
5173                        }
5174                        libs.add(libEntry.info.getName());
5175                        break;
5176                    }
5177                }
5178            }
5179
5180            if (libs != null) {
5181                String[] libsArray = new String[libs.size()];
5182                libs.toArray(libsArray);
5183                return libsArray;
5184            }
5185
5186            return null;
5187        }
5188    }
5189
5190    @Override
5191    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5192        // allow instant applications
5193        synchronized (mPackages) {
5194            return mServicesSystemSharedLibraryPackageName;
5195        }
5196    }
5197
5198    @Override
5199    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5200        // allow instant applications
5201        synchronized (mPackages) {
5202            return mSharedSystemSharedLibraryPackageName;
5203        }
5204    }
5205
5206    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5207        for (int i = userList.length - 1; i >= 0; --i) {
5208            final int userId = userList[i];
5209            // don't add instant app to the list of updates
5210            if (pkgSetting.getInstantApp(userId)) {
5211                continue;
5212            }
5213            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5214            if (changedPackages == null) {
5215                changedPackages = new SparseArray<>();
5216                mChangedPackages.put(userId, changedPackages);
5217            }
5218            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5219            if (sequenceNumbers == null) {
5220                sequenceNumbers = new HashMap<>();
5221                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5222            }
5223            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5224            if (sequenceNumber != null) {
5225                changedPackages.remove(sequenceNumber);
5226            }
5227            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5228            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5229        }
5230        mChangedPackagesSequenceNumber++;
5231    }
5232
5233    @Override
5234    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5235        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5236            return null;
5237        }
5238        synchronized (mPackages) {
5239            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5240                return null;
5241            }
5242            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5243            if (changedPackages == null) {
5244                return null;
5245            }
5246            final List<String> packageNames =
5247                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5248            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5249                final String packageName = changedPackages.get(i);
5250                if (packageName != null) {
5251                    packageNames.add(packageName);
5252                }
5253            }
5254            return packageNames.isEmpty()
5255                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5256        }
5257    }
5258
5259    @Override
5260    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5261        // allow instant applications
5262        ArrayList<FeatureInfo> res;
5263        synchronized (mAvailableFeatures) {
5264            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5265            res.addAll(mAvailableFeatures.values());
5266        }
5267        final FeatureInfo fi = new FeatureInfo();
5268        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5269                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5270        res.add(fi);
5271
5272        return new ParceledListSlice<>(res);
5273    }
5274
5275    @Override
5276    public boolean hasSystemFeature(String name, int version) {
5277        // allow instant applications
5278        synchronized (mAvailableFeatures) {
5279            final FeatureInfo feat = mAvailableFeatures.get(name);
5280            if (feat == null) {
5281                return false;
5282            } else {
5283                return feat.version >= version;
5284            }
5285        }
5286    }
5287
5288    @Override
5289    public int checkPermission(String permName, String pkgName, int userId) {
5290        if (!sUserManager.exists(userId)) {
5291            return PackageManager.PERMISSION_DENIED;
5292        }
5293        final int callingUid = Binder.getCallingUid();
5294
5295        synchronized (mPackages) {
5296            final PackageParser.Package p = mPackages.get(pkgName);
5297            if (p != null && p.mExtras != null) {
5298                final PackageSetting ps = (PackageSetting) p.mExtras;
5299                if (filterAppAccessLPr(ps, callingUid, userId)) {
5300                    return PackageManager.PERMISSION_DENIED;
5301                }
5302                final boolean instantApp = ps.getInstantApp(userId);
5303                final PermissionsState permissionsState = ps.getPermissionsState();
5304                if (permissionsState.hasPermission(permName, userId)) {
5305                    if (instantApp) {
5306                        BasePermission bp = mSettings.mPermissions.get(permName);
5307                        if (bp != null && bp.isInstant()) {
5308                            return PackageManager.PERMISSION_GRANTED;
5309                        }
5310                    } else {
5311                        return PackageManager.PERMISSION_GRANTED;
5312                    }
5313                }
5314                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5315                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5316                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5317                    return PackageManager.PERMISSION_GRANTED;
5318                }
5319            }
5320        }
5321
5322        return PackageManager.PERMISSION_DENIED;
5323    }
5324
5325    @Override
5326    public int checkUidPermission(String permName, int uid) {
5327        final int callingUid = Binder.getCallingUid();
5328        final int callingUserId = UserHandle.getUserId(callingUid);
5329        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5330        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5331        final int userId = UserHandle.getUserId(uid);
5332        if (!sUserManager.exists(userId)) {
5333            return PackageManager.PERMISSION_DENIED;
5334        }
5335
5336        synchronized (mPackages) {
5337            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5338            if (obj != null) {
5339                if (obj instanceof SharedUserSetting) {
5340                    if (isCallerInstantApp) {
5341                        return PackageManager.PERMISSION_DENIED;
5342                    }
5343                } else if (obj instanceof PackageSetting) {
5344                    final PackageSetting ps = (PackageSetting) obj;
5345                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5346                        return PackageManager.PERMISSION_DENIED;
5347                    }
5348                }
5349                final SettingBase settingBase = (SettingBase) obj;
5350                final PermissionsState permissionsState = settingBase.getPermissionsState();
5351                if (permissionsState.hasPermission(permName, userId)) {
5352                    if (isUidInstantApp) {
5353                        BasePermission bp = mSettings.mPermissions.get(permName);
5354                        if (bp != null && bp.isInstant()) {
5355                            return PackageManager.PERMISSION_GRANTED;
5356                        }
5357                    } else {
5358                        return PackageManager.PERMISSION_GRANTED;
5359                    }
5360                }
5361                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5362                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5363                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5364                    return PackageManager.PERMISSION_GRANTED;
5365                }
5366            } else {
5367                ArraySet<String> perms = mSystemPermissions.get(uid);
5368                if (perms != null) {
5369                    if (perms.contains(permName)) {
5370                        return PackageManager.PERMISSION_GRANTED;
5371                    }
5372                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5373                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5374                        return PackageManager.PERMISSION_GRANTED;
5375                    }
5376                }
5377            }
5378        }
5379
5380        return PackageManager.PERMISSION_DENIED;
5381    }
5382
5383    @Override
5384    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5385        if (UserHandle.getCallingUserId() != userId) {
5386            mContext.enforceCallingPermission(
5387                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5388                    "isPermissionRevokedByPolicy for user " + userId);
5389        }
5390
5391        if (checkPermission(permission, packageName, userId)
5392                == PackageManager.PERMISSION_GRANTED) {
5393            return false;
5394        }
5395
5396        final int callingUid = Binder.getCallingUid();
5397        if (getInstantAppPackageName(callingUid) != null) {
5398            if (!isCallerSameApp(packageName, callingUid)) {
5399                return false;
5400            }
5401        } else {
5402            if (isInstantApp(packageName, userId)) {
5403                return false;
5404            }
5405        }
5406
5407        final long identity = Binder.clearCallingIdentity();
5408        try {
5409            final int flags = getPermissionFlags(permission, packageName, userId);
5410            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5411        } finally {
5412            Binder.restoreCallingIdentity(identity);
5413        }
5414    }
5415
5416    @Override
5417    public String getPermissionControllerPackageName() {
5418        synchronized (mPackages) {
5419            return mRequiredInstallerPackage;
5420        }
5421    }
5422
5423    /**
5424     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5425     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5426     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5427     * @param message the message to log on security exception
5428     */
5429    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5430            boolean checkShell, String message) {
5431        if (userId < 0) {
5432            throw new IllegalArgumentException("Invalid userId " + userId);
5433        }
5434        if (checkShell) {
5435            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5436        }
5437        if (userId == UserHandle.getUserId(callingUid)) return;
5438        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5439            if (requireFullPermission) {
5440                mContext.enforceCallingOrSelfPermission(
5441                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5442            } else {
5443                try {
5444                    mContext.enforceCallingOrSelfPermission(
5445                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5446                } catch (SecurityException se) {
5447                    mContext.enforceCallingOrSelfPermission(
5448                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5449                }
5450            }
5451        }
5452    }
5453
5454    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5455        if (callingUid == Process.SHELL_UID) {
5456            if (userHandle >= 0
5457                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5458                throw new SecurityException("Shell does not have permission to access user "
5459                        + userHandle);
5460            } else if (userHandle < 0) {
5461                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5462                        + Debug.getCallers(3));
5463            }
5464        }
5465    }
5466
5467    private BasePermission findPermissionTreeLP(String permName) {
5468        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5469            if (permName.startsWith(bp.name) &&
5470                    permName.length() > bp.name.length() &&
5471                    permName.charAt(bp.name.length()) == '.') {
5472                return bp;
5473            }
5474        }
5475        return null;
5476    }
5477
5478    private BasePermission checkPermissionTreeLP(String permName) {
5479        if (permName != null) {
5480            BasePermission bp = findPermissionTreeLP(permName);
5481            if (bp != null) {
5482                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5483                    return bp;
5484                }
5485                throw new SecurityException("Calling uid "
5486                        + Binder.getCallingUid()
5487                        + " is not allowed to add to permission tree "
5488                        + bp.name + " owned by uid " + bp.uid);
5489            }
5490        }
5491        throw new SecurityException("No permission tree found for " + permName);
5492    }
5493
5494    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5495        if (s1 == null) {
5496            return s2 == null;
5497        }
5498        if (s2 == null) {
5499            return false;
5500        }
5501        if (s1.getClass() != s2.getClass()) {
5502            return false;
5503        }
5504        return s1.equals(s2);
5505    }
5506
5507    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5508        if (pi1.icon != pi2.icon) return false;
5509        if (pi1.logo != pi2.logo) return false;
5510        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5511        if (!compareStrings(pi1.name, pi2.name)) return false;
5512        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5513        // We'll take care of setting this one.
5514        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5515        // These are not currently stored in settings.
5516        //if (!compareStrings(pi1.group, pi2.group)) return false;
5517        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5518        //if (pi1.labelRes != pi2.labelRes) return false;
5519        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5520        return true;
5521    }
5522
5523    int permissionInfoFootprint(PermissionInfo info) {
5524        int size = info.name.length();
5525        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5526        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5527        return size;
5528    }
5529
5530    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5531        int size = 0;
5532        for (BasePermission perm : mSettings.mPermissions.values()) {
5533            if (perm.uid == tree.uid) {
5534                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5535            }
5536        }
5537        return size;
5538    }
5539
5540    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5541        // We calculate the max size of permissions defined by this uid and throw
5542        // if that plus the size of 'info' would exceed our stated maximum.
5543        if (tree.uid != Process.SYSTEM_UID) {
5544            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5545            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5546                throw new SecurityException("Permission tree size cap exceeded");
5547            }
5548        }
5549    }
5550
5551    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5552        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5553            throw new SecurityException("Instant apps can't add permissions");
5554        }
5555        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5556            throw new SecurityException("Label must be specified in permission");
5557        }
5558        BasePermission tree = checkPermissionTreeLP(info.name);
5559        BasePermission bp = mSettings.mPermissions.get(info.name);
5560        boolean added = bp == null;
5561        boolean changed = true;
5562        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5563        if (added) {
5564            enforcePermissionCapLocked(info, tree);
5565            bp = new BasePermission(info.name, tree.sourcePackage,
5566                    BasePermission.TYPE_DYNAMIC);
5567        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5568            throw new SecurityException(
5569                    "Not allowed to modify non-dynamic permission "
5570                    + info.name);
5571        } else {
5572            if (bp.protectionLevel == fixedLevel
5573                    && bp.perm.owner.equals(tree.perm.owner)
5574                    && bp.uid == tree.uid
5575                    && comparePermissionInfos(bp.perm.info, info)) {
5576                changed = false;
5577            }
5578        }
5579        bp.protectionLevel = fixedLevel;
5580        info = new PermissionInfo(info);
5581        info.protectionLevel = fixedLevel;
5582        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5583        bp.perm.info.packageName = tree.perm.info.packageName;
5584        bp.uid = tree.uid;
5585        if (added) {
5586            mSettings.mPermissions.put(info.name, bp);
5587        }
5588        if (changed) {
5589            if (!async) {
5590                mSettings.writeLPr();
5591            } else {
5592                scheduleWriteSettingsLocked();
5593            }
5594        }
5595        return added;
5596    }
5597
5598    @Override
5599    public boolean addPermission(PermissionInfo info) {
5600        synchronized (mPackages) {
5601            return addPermissionLocked(info, false);
5602        }
5603    }
5604
5605    @Override
5606    public boolean addPermissionAsync(PermissionInfo info) {
5607        synchronized (mPackages) {
5608            return addPermissionLocked(info, true);
5609        }
5610    }
5611
5612    @Override
5613    public void removePermission(String name) {
5614        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5615            throw new SecurityException("Instant applications don't have access to this method");
5616        }
5617        synchronized (mPackages) {
5618            checkPermissionTreeLP(name);
5619            BasePermission bp = mSettings.mPermissions.get(name);
5620            if (bp != null) {
5621                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5622                    throw new SecurityException(
5623                            "Not allowed to modify non-dynamic permission "
5624                            + name);
5625                }
5626                mSettings.mPermissions.remove(name);
5627                mSettings.writeLPr();
5628            }
5629        }
5630    }
5631
5632    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5633            PackageParser.Package pkg, BasePermission bp) {
5634        int index = pkg.requestedPermissions.indexOf(bp.name);
5635        if (index == -1) {
5636            throw new SecurityException("Package " + pkg.packageName
5637                    + " has not requested permission " + bp.name);
5638        }
5639        if (!bp.isRuntime() && !bp.isDevelopment()) {
5640            throw new SecurityException("Permission " + bp.name
5641                    + " is not a changeable permission type");
5642        }
5643    }
5644
5645    @Override
5646    public void grantRuntimePermission(String packageName, String name, final int userId) {
5647        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5648    }
5649
5650    private void grantRuntimePermission(String packageName, String name, final int userId,
5651            boolean overridePolicy) {
5652        if (!sUserManager.exists(userId)) {
5653            Log.e(TAG, "No such user:" + userId);
5654            return;
5655        }
5656        final int callingUid = Binder.getCallingUid();
5657
5658        mContext.enforceCallingOrSelfPermission(
5659                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5660                "grantRuntimePermission");
5661
5662        enforceCrossUserPermission(callingUid, userId,
5663                true /* requireFullPermission */, true /* checkShell */,
5664                "grantRuntimePermission");
5665
5666        final int uid;
5667        final PackageSetting ps;
5668
5669        synchronized (mPackages) {
5670            final PackageParser.Package pkg = mPackages.get(packageName);
5671            if (pkg == null) {
5672                throw new IllegalArgumentException("Unknown package: " + packageName);
5673            }
5674            final BasePermission bp = mSettings.mPermissions.get(name);
5675            if (bp == null) {
5676                throw new IllegalArgumentException("Unknown permission: " + name);
5677            }
5678            ps = (PackageSetting) pkg.mExtras;
5679            if (ps == null
5680                    || filterAppAccessLPr(ps, callingUid, userId)) {
5681                throw new IllegalArgumentException("Unknown package: " + packageName);
5682            }
5683
5684            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5685
5686            // If a permission review is required for legacy apps we represent
5687            // their permissions as always granted runtime ones since we need
5688            // to keep the review required permission flag per user while an
5689            // install permission's state is shared across all users.
5690            if (mPermissionReviewRequired
5691                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5692                    && bp.isRuntime()) {
5693                return;
5694            }
5695
5696            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5697
5698            final PermissionsState permissionsState = ps.getPermissionsState();
5699
5700            final int flags = permissionsState.getPermissionFlags(name, userId);
5701            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5702                throw new SecurityException("Cannot grant system fixed permission "
5703                        + name + " for package " + packageName);
5704            }
5705            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5706                throw new SecurityException("Cannot grant policy fixed permission "
5707                        + name + " for package " + packageName);
5708            }
5709
5710            if (bp.isDevelopment()) {
5711                // Development permissions must be handled specially, since they are not
5712                // normal runtime permissions.  For now they apply to all users.
5713                if (permissionsState.grantInstallPermission(bp) !=
5714                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5715                    scheduleWriteSettingsLocked();
5716                }
5717                return;
5718            }
5719
5720            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5721                throw new SecurityException("Cannot grant non-ephemeral permission"
5722                        + name + " for package " + packageName);
5723            }
5724
5725            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5726                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5727                return;
5728            }
5729
5730            final int result = permissionsState.grantRuntimePermission(bp, userId);
5731            switch (result) {
5732                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5733                    return;
5734                }
5735
5736                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5737                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5738                    mHandler.post(new Runnable() {
5739                        @Override
5740                        public void run() {
5741                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5742                        }
5743                    });
5744                }
5745                break;
5746            }
5747
5748            if (bp.isRuntime()) {
5749                logPermissionGranted(mContext, name, packageName);
5750            }
5751
5752            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5753
5754            // Not critical if that is lost - app has to request again.
5755            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5756        }
5757
5758        // Only need to do this if user is initialized. Otherwise it's a new user
5759        // and there are no processes running as the user yet and there's no need
5760        // to make an expensive call to remount processes for the changed permissions.
5761        if (READ_EXTERNAL_STORAGE.equals(name)
5762                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5763            final long token = Binder.clearCallingIdentity();
5764            try {
5765                if (sUserManager.isInitialized(userId)) {
5766                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5767                            StorageManagerInternal.class);
5768                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5769                }
5770            } finally {
5771                Binder.restoreCallingIdentity(token);
5772            }
5773        }
5774    }
5775
5776    @Override
5777    public void revokeRuntimePermission(String packageName, String name, int userId) {
5778        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5779    }
5780
5781    private void revokeRuntimePermission(String packageName, String name, int userId,
5782            boolean overridePolicy) {
5783        if (!sUserManager.exists(userId)) {
5784            Log.e(TAG, "No such user:" + userId);
5785            return;
5786        }
5787
5788        mContext.enforceCallingOrSelfPermission(
5789                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5790                "revokeRuntimePermission");
5791
5792        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5793                true /* requireFullPermission */, true /* checkShell */,
5794                "revokeRuntimePermission");
5795
5796        final int appId;
5797
5798        synchronized (mPackages) {
5799            final PackageParser.Package pkg = mPackages.get(packageName);
5800            if (pkg == null) {
5801                throw new IllegalArgumentException("Unknown package: " + packageName);
5802            }
5803            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5804            if (ps == null
5805                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5806                throw new IllegalArgumentException("Unknown package: " + packageName);
5807            }
5808            final BasePermission bp = mSettings.mPermissions.get(name);
5809            if (bp == null) {
5810                throw new IllegalArgumentException("Unknown permission: " + name);
5811            }
5812
5813            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5814
5815            // If a permission review is required for legacy apps we represent
5816            // their permissions as always granted runtime ones since we need
5817            // to keep the review required permission flag per user while an
5818            // install permission's state is shared across all users.
5819            if (mPermissionReviewRequired
5820                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5821                    && bp.isRuntime()) {
5822                return;
5823            }
5824
5825            final PermissionsState permissionsState = ps.getPermissionsState();
5826
5827            final int flags = permissionsState.getPermissionFlags(name, userId);
5828            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5829                throw new SecurityException("Cannot revoke system fixed permission "
5830                        + name + " for package " + packageName);
5831            }
5832            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5833                throw new SecurityException("Cannot revoke policy fixed permission "
5834                        + name + " for package " + packageName);
5835            }
5836
5837            if (bp.isDevelopment()) {
5838                // Development permissions must be handled specially, since they are not
5839                // normal runtime permissions.  For now they apply to all users.
5840                if (permissionsState.revokeInstallPermission(bp) !=
5841                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5842                    scheduleWriteSettingsLocked();
5843                }
5844                return;
5845            }
5846
5847            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5848                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5849                return;
5850            }
5851
5852            if (bp.isRuntime()) {
5853                logPermissionRevoked(mContext, name, packageName);
5854            }
5855
5856            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5857
5858            // Critical, after this call app should never have the permission.
5859            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5860
5861            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5862        }
5863
5864        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5865    }
5866
5867    /**
5868     * Get the first event id for the permission.
5869     *
5870     * <p>There are four events for each permission: <ul>
5871     *     <li>Request permission: first id + 0</li>
5872     *     <li>Grant permission: first id + 1</li>
5873     *     <li>Request for permission denied: first id + 2</li>
5874     *     <li>Revoke permission: first id + 3</li>
5875     * </ul></p>
5876     *
5877     * @param name name of the permission
5878     *
5879     * @return The first event id for the permission
5880     */
5881    private static int getBaseEventId(@NonNull String name) {
5882        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5883
5884        if (eventIdIndex == -1) {
5885            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5886                    || Build.IS_USER) {
5887                Log.i(TAG, "Unknown permission " + name);
5888
5889                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5890            } else {
5891                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5892                //
5893                // Also update
5894                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5895                // - metrics_constants.proto
5896                throw new IllegalStateException("Unknown permission " + name);
5897            }
5898        }
5899
5900        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5901    }
5902
5903    /**
5904     * Log that a permission was revoked.
5905     *
5906     * @param context Context of the caller
5907     * @param name name of the permission
5908     * @param packageName package permission if for
5909     */
5910    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5911            @NonNull String packageName) {
5912        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5913    }
5914
5915    /**
5916     * Log that a permission request was granted.
5917     *
5918     * @param context Context of the caller
5919     * @param name name of the permission
5920     * @param packageName package permission if for
5921     */
5922    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5923            @NonNull String packageName) {
5924        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5925    }
5926
5927    @Override
5928    public void resetRuntimePermissions() {
5929        mContext.enforceCallingOrSelfPermission(
5930                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5931                "revokeRuntimePermission");
5932
5933        int callingUid = Binder.getCallingUid();
5934        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5935            mContext.enforceCallingOrSelfPermission(
5936                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5937                    "resetRuntimePermissions");
5938        }
5939
5940        synchronized (mPackages) {
5941            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5942            for (int userId : UserManagerService.getInstance().getUserIds()) {
5943                final int packageCount = mPackages.size();
5944                for (int i = 0; i < packageCount; i++) {
5945                    PackageParser.Package pkg = mPackages.valueAt(i);
5946                    if (!(pkg.mExtras instanceof PackageSetting)) {
5947                        continue;
5948                    }
5949                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5950                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5951                }
5952            }
5953        }
5954    }
5955
5956    @Override
5957    public int getPermissionFlags(String name, String packageName, int userId) {
5958        if (!sUserManager.exists(userId)) {
5959            return 0;
5960        }
5961
5962        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5963
5964        final int callingUid = Binder.getCallingUid();
5965        enforceCrossUserPermission(callingUid, userId,
5966                true /* requireFullPermission */, false /* checkShell */,
5967                "getPermissionFlags");
5968
5969        synchronized (mPackages) {
5970            final PackageParser.Package pkg = mPackages.get(packageName);
5971            if (pkg == null) {
5972                return 0;
5973            }
5974            final BasePermission bp = mSettings.mPermissions.get(name);
5975            if (bp == null) {
5976                return 0;
5977            }
5978            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5979            if (ps == null
5980                    || filterAppAccessLPr(ps, callingUid, userId)) {
5981                return 0;
5982            }
5983            PermissionsState permissionsState = ps.getPermissionsState();
5984            return permissionsState.getPermissionFlags(name, userId);
5985        }
5986    }
5987
5988    @Override
5989    public void updatePermissionFlags(String name, String packageName, int flagMask,
5990            int flagValues, int userId) {
5991        if (!sUserManager.exists(userId)) {
5992            return;
5993        }
5994
5995        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5996
5997        final int callingUid = Binder.getCallingUid();
5998        enforceCrossUserPermission(callingUid, userId,
5999                true /* requireFullPermission */, true /* checkShell */,
6000                "updatePermissionFlags");
6001
6002        // Only the system can change these flags and nothing else.
6003        if (getCallingUid() != Process.SYSTEM_UID) {
6004            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6005            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6006            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
6007            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
6008            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
6009        }
6010
6011        synchronized (mPackages) {
6012            final PackageParser.Package pkg = mPackages.get(packageName);
6013            if (pkg == null) {
6014                throw new IllegalArgumentException("Unknown package: " + packageName);
6015            }
6016            final PackageSetting ps = (PackageSetting) pkg.mExtras;
6017            if (ps == null
6018                    || filterAppAccessLPr(ps, callingUid, userId)) {
6019                throw new IllegalArgumentException("Unknown package: " + packageName);
6020            }
6021
6022            final BasePermission bp = mSettings.mPermissions.get(name);
6023            if (bp == null) {
6024                throw new IllegalArgumentException("Unknown permission: " + name);
6025            }
6026
6027            PermissionsState permissionsState = ps.getPermissionsState();
6028
6029            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6030
6031            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6032                // Install and runtime permissions are stored in different places,
6033                // so figure out what permission changed and persist the change.
6034                if (permissionsState.getInstallPermissionState(name) != null) {
6035                    scheduleWriteSettingsLocked();
6036                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6037                        || hadState) {
6038                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6039                }
6040            }
6041        }
6042    }
6043
6044    /**
6045     * Update the permission flags for all packages and runtime permissions of a user in order
6046     * to allow device or profile owner to remove POLICY_FIXED.
6047     */
6048    @Override
6049    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6050        if (!sUserManager.exists(userId)) {
6051            return;
6052        }
6053
6054        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6055
6056        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6057                true /* requireFullPermission */, true /* checkShell */,
6058                "updatePermissionFlagsForAllApps");
6059
6060        // Only the system can change system fixed flags.
6061        if (getCallingUid() != Process.SYSTEM_UID) {
6062            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6063            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6064        }
6065
6066        synchronized (mPackages) {
6067            boolean changed = false;
6068            final int packageCount = mPackages.size();
6069            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6070                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6071                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6072                if (ps == null) {
6073                    continue;
6074                }
6075                PermissionsState permissionsState = ps.getPermissionsState();
6076                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6077                        userId, flagMask, flagValues);
6078            }
6079            if (changed) {
6080                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6081            }
6082        }
6083    }
6084
6085    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6086        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6087                != PackageManager.PERMISSION_GRANTED
6088            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6089                != PackageManager.PERMISSION_GRANTED) {
6090            throw new SecurityException(message + " requires "
6091                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6092                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6093        }
6094    }
6095
6096    @Override
6097    public boolean shouldShowRequestPermissionRationale(String permissionName,
6098            String packageName, int userId) {
6099        if (UserHandle.getCallingUserId() != userId) {
6100            mContext.enforceCallingPermission(
6101                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6102                    "canShowRequestPermissionRationale for user " + userId);
6103        }
6104
6105        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6106        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6107            return false;
6108        }
6109
6110        if (checkPermission(permissionName, packageName, userId)
6111                == PackageManager.PERMISSION_GRANTED) {
6112            return false;
6113        }
6114
6115        final int flags;
6116
6117        final long identity = Binder.clearCallingIdentity();
6118        try {
6119            flags = getPermissionFlags(permissionName,
6120                    packageName, userId);
6121        } finally {
6122            Binder.restoreCallingIdentity(identity);
6123        }
6124
6125        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6126                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6127                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6128
6129        if ((flags & fixedFlags) != 0) {
6130            return false;
6131        }
6132
6133        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6134    }
6135
6136    @Override
6137    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6138        mContext.enforceCallingOrSelfPermission(
6139                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6140                "addOnPermissionsChangeListener");
6141
6142        synchronized (mPackages) {
6143            mOnPermissionChangeListeners.addListenerLocked(listener);
6144        }
6145    }
6146
6147    @Override
6148    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6149        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6150            throw new SecurityException("Instant applications don't have access to this method");
6151        }
6152        synchronized (mPackages) {
6153            mOnPermissionChangeListeners.removeListenerLocked(listener);
6154        }
6155    }
6156
6157    @Override
6158    public boolean isProtectedBroadcast(String actionName) {
6159        // allow instant applications
6160        synchronized (mProtectedBroadcasts) {
6161            if (mProtectedBroadcasts.contains(actionName)) {
6162                return true;
6163            } else if (actionName != null) {
6164                // TODO: remove these terrible hacks
6165                if (actionName.startsWith("android.net.netmon.lingerExpired")
6166                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6167                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6168                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6169                    return true;
6170                }
6171            }
6172        }
6173        return false;
6174    }
6175
6176    @Override
6177    public int checkSignatures(String pkg1, String pkg2) {
6178        synchronized (mPackages) {
6179            final PackageParser.Package p1 = mPackages.get(pkg1);
6180            final PackageParser.Package p2 = mPackages.get(pkg2);
6181            if (p1 == null || p1.mExtras == null
6182                    || p2 == null || p2.mExtras == null) {
6183                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6184            }
6185            final int callingUid = Binder.getCallingUid();
6186            final int callingUserId = UserHandle.getUserId(callingUid);
6187            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6188            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6189            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6190                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6191                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6192            }
6193            return compareSignatures(p1.mSignatures, p2.mSignatures);
6194        }
6195    }
6196
6197    @Override
6198    public int checkUidSignatures(int uid1, int uid2) {
6199        final int callingUid = Binder.getCallingUid();
6200        final int callingUserId = UserHandle.getUserId(callingUid);
6201        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6202        // Map to base uids.
6203        uid1 = UserHandle.getAppId(uid1);
6204        uid2 = UserHandle.getAppId(uid2);
6205        // reader
6206        synchronized (mPackages) {
6207            Signature[] s1;
6208            Signature[] s2;
6209            Object obj = mSettings.getUserIdLPr(uid1);
6210            if (obj != null) {
6211                if (obj instanceof SharedUserSetting) {
6212                    if (isCallerInstantApp) {
6213                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6214                    }
6215                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6216                } else if (obj instanceof PackageSetting) {
6217                    final PackageSetting ps = (PackageSetting) obj;
6218                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6219                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6220                    }
6221                    s1 = ps.signatures.mSignatures;
6222                } else {
6223                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6224                }
6225            } else {
6226                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6227            }
6228            obj = mSettings.getUserIdLPr(uid2);
6229            if (obj != null) {
6230                if (obj instanceof SharedUserSetting) {
6231                    if (isCallerInstantApp) {
6232                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6233                    }
6234                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6235                } else if (obj instanceof PackageSetting) {
6236                    final PackageSetting ps = (PackageSetting) obj;
6237                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6238                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6239                    }
6240                    s2 = ps.signatures.mSignatures;
6241                } else {
6242                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6243                }
6244            } else {
6245                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6246            }
6247            return compareSignatures(s1, s2);
6248        }
6249    }
6250
6251    /**
6252     * This method should typically only be used when granting or revoking
6253     * permissions, since the app may immediately restart after this call.
6254     * <p>
6255     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6256     * guard your work against the app being relaunched.
6257     */
6258    private void killUid(int appId, int userId, String reason) {
6259        final long identity = Binder.clearCallingIdentity();
6260        try {
6261            IActivityManager am = ActivityManager.getService();
6262            if (am != null) {
6263                try {
6264                    am.killUid(appId, userId, reason);
6265                } catch (RemoteException e) {
6266                    /* ignore - same process */
6267                }
6268            }
6269        } finally {
6270            Binder.restoreCallingIdentity(identity);
6271        }
6272    }
6273
6274    /**
6275     * Compares two sets of signatures. Returns:
6276     * <br />
6277     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6278     * <br />
6279     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6280     * <br />
6281     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6282     * <br />
6283     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6284     * <br />
6285     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6286     */
6287    static int compareSignatures(Signature[] s1, Signature[] s2) {
6288        if (s1 == null) {
6289            return s2 == null
6290                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6291                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6292        }
6293
6294        if (s2 == null) {
6295            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6296        }
6297
6298        if (s1.length != s2.length) {
6299            return PackageManager.SIGNATURE_NO_MATCH;
6300        }
6301
6302        // Since both signature sets are of size 1, we can compare without HashSets.
6303        if (s1.length == 1) {
6304            return s1[0].equals(s2[0]) ?
6305                    PackageManager.SIGNATURE_MATCH :
6306                    PackageManager.SIGNATURE_NO_MATCH;
6307        }
6308
6309        ArraySet<Signature> set1 = new ArraySet<Signature>();
6310        for (Signature sig : s1) {
6311            set1.add(sig);
6312        }
6313        ArraySet<Signature> set2 = new ArraySet<Signature>();
6314        for (Signature sig : s2) {
6315            set2.add(sig);
6316        }
6317        // Make sure s2 contains all signatures in s1.
6318        if (set1.equals(set2)) {
6319            return PackageManager.SIGNATURE_MATCH;
6320        }
6321        return PackageManager.SIGNATURE_NO_MATCH;
6322    }
6323
6324    /**
6325     * If the database version for this type of package (internal storage or
6326     * external storage) is less than the version where package signatures
6327     * were updated, return true.
6328     */
6329    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6330        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6331        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6332    }
6333
6334    /**
6335     * Used for backward compatibility to make sure any packages with
6336     * certificate chains get upgraded to the new style. {@code existingSigs}
6337     * will be in the old format (since they were stored on disk from before the
6338     * system upgrade) and {@code scannedSigs} will be in the newer format.
6339     */
6340    private int compareSignaturesCompat(PackageSignatures existingSigs,
6341            PackageParser.Package scannedPkg) {
6342        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6343            return PackageManager.SIGNATURE_NO_MATCH;
6344        }
6345
6346        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6347        for (Signature sig : existingSigs.mSignatures) {
6348            existingSet.add(sig);
6349        }
6350        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6351        for (Signature sig : scannedPkg.mSignatures) {
6352            try {
6353                Signature[] chainSignatures = sig.getChainSignatures();
6354                for (Signature chainSig : chainSignatures) {
6355                    scannedCompatSet.add(chainSig);
6356                }
6357            } catch (CertificateEncodingException e) {
6358                scannedCompatSet.add(sig);
6359            }
6360        }
6361        /*
6362         * Make sure the expanded scanned set contains all signatures in the
6363         * existing one.
6364         */
6365        if (scannedCompatSet.equals(existingSet)) {
6366            // Migrate the old signatures to the new scheme.
6367            existingSigs.assignSignatures(scannedPkg.mSignatures);
6368            // The new KeySets will be re-added later in the scanning process.
6369            synchronized (mPackages) {
6370                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6371            }
6372            return PackageManager.SIGNATURE_MATCH;
6373        }
6374        return PackageManager.SIGNATURE_NO_MATCH;
6375    }
6376
6377    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6378        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6379        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6380    }
6381
6382    private int compareSignaturesRecover(PackageSignatures existingSigs,
6383            PackageParser.Package scannedPkg) {
6384        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6385            return PackageManager.SIGNATURE_NO_MATCH;
6386        }
6387
6388        String msg = null;
6389        try {
6390            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6391                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6392                        + scannedPkg.packageName);
6393                return PackageManager.SIGNATURE_MATCH;
6394            }
6395        } catch (CertificateException e) {
6396            msg = e.getMessage();
6397        }
6398
6399        logCriticalInfo(Log.INFO,
6400                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6401        return PackageManager.SIGNATURE_NO_MATCH;
6402    }
6403
6404    @Override
6405    public List<String> getAllPackages() {
6406        final int callingUid = Binder.getCallingUid();
6407        final int callingUserId = UserHandle.getUserId(callingUid);
6408        synchronized (mPackages) {
6409            if (canViewInstantApps(callingUid, callingUserId)) {
6410                return new ArrayList<String>(mPackages.keySet());
6411            }
6412            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6413            final List<String> result = new ArrayList<>();
6414            if (instantAppPkgName != null) {
6415                // caller is an instant application; filter unexposed applications
6416                for (PackageParser.Package pkg : mPackages.values()) {
6417                    if (!pkg.visibleToInstantApps) {
6418                        continue;
6419                    }
6420                    result.add(pkg.packageName);
6421                }
6422            } else {
6423                // caller is a normal application; filter instant applications
6424                for (PackageParser.Package pkg : mPackages.values()) {
6425                    final PackageSetting ps =
6426                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6427                    if (ps != null
6428                            && ps.getInstantApp(callingUserId)
6429                            && !mInstantAppRegistry.isInstantAccessGranted(
6430                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6431                        continue;
6432                    }
6433                    result.add(pkg.packageName);
6434                }
6435            }
6436            return result;
6437        }
6438    }
6439
6440    @Override
6441    public String[] getPackagesForUid(int uid) {
6442        final int callingUid = Binder.getCallingUid();
6443        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6444        final int userId = UserHandle.getUserId(uid);
6445        uid = UserHandle.getAppId(uid);
6446        // reader
6447        synchronized (mPackages) {
6448            Object obj = mSettings.getUserIdLPr(uid);
6449            if (obj instanceof SharedUserSetting) {
6450                if (isCallerInstantApp) {
6451                    return null;
6452                }
6453                final SharedUserSetting sus = (SharedUserSetting) obj;
6454                final int N = sus.packages.size();
6455                String[] res = new String[N];
6456                final Iterator<PackageSetting> it = sus.packages.iterator();
6457                int i = 0;
6458                while (it.hasNext()) {
6459                    PackageSetting ps = it.next();
6460                    if (ps.getInstalled(userId)) {
6461                        res[i++] = ps.name;
6462                    } else {
6463                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6464                    }
6465                }
6466                return res;
6467            } else if (obj instanceof PackageSetting) {
6468                final PackageSetting ps = (PackageSetting) obj;
6469                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6470                    return new String[]{ps.name};
6471                }
6472            }
6473        }
6474        return null;
6475    }
6476
6477    @Override
6478    public String getNameForUid(int uid) {
6479        final int callingUid = Binder.getCallingUid();
6480        if (getInstantAppPackageName(callingUid) != null) {
6481            return null;
6482        }
6483        synchronized (mPackages) {
6484            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6485            if (obj instanceof SharedUserSetting) {
6486                final SharedUserSetting sus = (SharedUserSetting) obj;
6487                return sus.name + ":" + sus.userId;
6488            } else if (obj instanceof PackageSetting) {
6489                final PackageSetting ps = (PackageSetting) obj;
6490                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6491                    return null;
6492                }
6493                return ps.name;
6494            }
6495            return null;
6496        }
6497    }
6498
6499    @Override
6500    public String[] getNamesForUids(int[] uids) {
6501        if (uids == null || uids.length == 0) {
6502            return null;
6503        }
6504        final int callingUid = Binder.getCallingUid();
6505        if (getInstantAppPackageName(callingUid) != null) {
6506            return null;
6507        }
6508        final String[] names = new String[uids.length];
6509        synchronized (mPackages) {
6510            for (int i = uids.length - 1; i >= 0; i--) {
6511                final int uid = uids[i];
6512                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6513                if (obj instanceof SharedUserSetting) {
6514                    final SharedUserSetting sus = (SharedUserSetting) obj;
6515                    names[i] = "shared:" + sus.name;
6516                } else if (obj instanceof PackageSetting) {
6517                    final PackageSetting ps = (PackageSetting) obj;
6518                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6519                        names[i] = null;
6520                    } else {
6521                        names[i] = ps.name;
6522                    }
6523                } else {
6524                    names[i] = null;
6525                }
6526            }
6527        }
6528        return names;
6529    }
6530
6531    @Override
6532    public int getUidForSharedUser(String sharedUserName) {
6533        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6534            return -1;
6535        }
6536        if (sharedUserName == null) {
6537            return -1;
6538        }
6539        // reader
6540        synchronized (mPackages) {
6541            SharedUserSetting suid;
6542            try {
6543                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6544                if (suid != null) {
6545                    return suid.userId;
6546                }
6547            } catch (PackageManagerException ignore) {
6548                // can't happen, but, still need to catch it
6549            }
6550            return -1;
6551        }
6552    }
6553
6554    @Override
6555    public int getFlagsForUid(int uid) {
6556        final int callingUid = Binder.getCallingUid();
6557        if (getInstantAppPackageName(callingUid) != null) {
6558            return 0;
6559        }
6560        synchronized (mPackages) {
6561            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6562            if (obj instanceof SharedUserSetting) {
6563                final SharedUserSetting sus = (SharedUserSetting) obj;
6564                return sus.pkgFlags;
6565            } else if (obj instanceof PackageSetting) {
6566                final PackageSetting ps = (PackageSetting) obj;
6567                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6568                    return 0;
6569                }
6570                return ps.pkgFlags;
6571            }
6572        }
6573        return 0;
6574    }
6575
6576    @Override
6577    public int getPrivateFlagsForUid(int uid) {
6578        final int callingUid = Binder.getCallingUid();
6579        if (getInstantAppPackageName(callingUid) != null) {
6580            return 0;
6581        }
6582        synchronized (mPackages) {
6583            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6584            if (obj instanceof SharedUserSetting) {
6585                final SharedUserSetting sus = (SharedUserSetting) obj;
6586                return sus.pkgPrivateFlags;
6587            } else if (obj instanceof PackageSetting) {
6588                final PackageSetting ps = (PackageSetting) obj;
6589                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6590                    return 0;
6591                }
6592                return ps.pkgPrivateFlags;
6593            }
6594        }
6595        return 0;
6596    }
6597
6598    @Override
6599    public boolean isUidPrivileged(int uid) {
6600        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6601            return false;
6602        }
6603        uid = UserHandle.getAppId(uid);
6604        // reader
6605        synchronized (mPackages) {
6606            Object obj = mSettings.getUserIdLPr(uid);
6607            if (obj instanceof SharedUserSetting) {
6608                final SharedUserSetting sus = (SharedUserSetting) obj;
6609                final Iterator<PackageSetting> it = sus.packages.iterator();
6610                while (it.hasNext()) {
6611                    if (it.next().isPrivileged()) {
6612                        return true;
6613                    }
6614                }
6615            } else if (obj instanceof PackageSetting) {
6616                final PackageSetting ps = (PackageSetting) obj;
6617                return ps.isPrivileged();
6618            }
6619        }
6620        return false;
6621    }
6622
6623    @Override
6624    public String[] getAppOpPermissionPackages(String permissionName) {
6625        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6626            return null;
6627        }
6628        synchronized (mPackages) {
6629            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6630            if (pkgs == null) {
6631                return null;
6632            }
6633            return pkgs.toArray(new String[pkgs.size()]);
6634        }
6635    }
6636
6637    @Override
6638    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6639            int flags, int userId) {
6640        return resolveIntentInternal(
6641                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6642    }
6643
6644    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6645            int flags, int userId, boolean resolveForStart) {
6646        try {
6647            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6648
6649            if (!sUserManager.exists(userId)) return null;
6650            final int callingUid = Binder.getCallingUid();
6651            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6652            enforceCrossUserPermission(callingUid, userId,
6653                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6654
6655            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6656            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6657                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6658            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6659
6660            final ResolveInfo bestChoice =
6661                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6662            return bestChoice;
6663        } finally {
6664            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6665        }
6666    }
6667
6668    @Override
6669    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6670        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6671            throw new SecurityException(
6672                    "findPersistentPreferredActivity can only be run by the system");
6673        }
6674        if (!sUserManager.exists(userId)) {
6675            return null;
6676        }
6677        final int callingUid = Binder.getCallingUid();
6678        intent = updateIntentForResolve(intent);
6679        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6680        final int flags = updateFlagsForResolve(
6681                0, userId, intent, callingUid, false /*includeInstantApps*/);
6682        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6683                userId);
6684        synchronized (mPackages) {
6685            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6686                    userId);
6687        }
6688    }
6689
6690    @Override
6691    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6692            IntentFilter filter, int match, ComponentName activity) {
6693        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6694            return;
6695        }
6696        final int userId = UserHandle.getCallingUserId();
6697        if (DEBUG_PREFERRED) {
6698            Log.v(TAG, "setLastChosenActivity intent=" + intent
6699                + " resolvedType=" + resolvedType
6700                + " flags=" + flags
6701                + " filter=" + filter
6702                + " match=" + match
6703                + " activity=" + activity);
6704            filter.dump(new PrintStreamPrinter(System.out), "    ");
6705        }
6706        intent.setComponent(null);
6707        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6708                userId);
6709        // Find any earlier preferred or last chosen entries and nuke them
6710        findPreferredActivity(intent, resolvedType,
6711                flags, query, 0, false, true, false, userId);
6712        // Add the new activity as the last chosen for this filter
6713        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6714                "Setting last chosen");
6715    }
6716
6717    @Override
6718    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6719        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6720            return null;
6721        }
6722        final int userId = UserHandle.getCallingUserId();
6723        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6724        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6725                userId);
6726        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6727                false, false, false, userId);
6728    }
6729
6730    /**
6731     * Returns whether or not instant apps have been disabled remotely.
6732     */
6733    private boolean isEphemeralDisabled() {
6734        return mEphemeralAppsDisabled;
6735    }
6736
6737    private boolean isInstantAppAllowed(
6738            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6739            boolean skipPackageCheck) {
6740        if (mInstantAppResolverConnection == null) {
6741            return false;
6742        }
6743        if (mInstantAppInstallerActivity == null) {
6744            return false;
6745        }
6746        if (intent.getComponent() != null) {
6747            return false;
6748        }
6749        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6750            return false;
6751        }
6752        if (!skipPackageCheck && intent.getPackage() != null) {
6753            return false;
6754        }
6755        final boolean isWebUri = hasWebURI(intent);
6756        if (!isWebUri || intent.getData().getHost() == null) {
6757            return false;
6758        }
6759        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6760        // Or if there's already an ephemeral app installed that handles the action
6761        synchronized (mPackages) {
6762            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6763            for (int n = 0; n < count; n++) {
6764                final ResolveInfo info = resolvedActivities.get(n);
6765                final String packageName = info.activityInfo.packageName;
6766                final PackageSetting ps = mSettings.mPackages.get(packageName);
6767                if (ps != null) {
6768                    // only check domain verification status if the app is not a browser
6769                    if (!info.handleAllWebDataURI) {
6770                        // Try to get the status from User settings first
6771                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6772                        final int status = (int) (packedStatus >> 32);
6773                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6774                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6775                            if (DEBUG_EPHEMERAL) {
6776                                Slog.v(TAG, "DENY instant app;"
6777                                    + " pkg: " + packageName + ", status: " + status);
6778                            }
6779                            return false;
6780                        }
6781                    }
6782                    if (ps.getInstantApp(userId)) {
6783                        if (DEBUG_EPHEMERAL) {
6784                            Slog.v(TAG, "DENY instant app installed;"
6785                                    + " pkg: " + packageName);
6786                        }
6787                        return false;
6788                    }
6789                }
6790            }
6791        }
6792        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6793        return true;
6794    }
6795
6796    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6797            Intent origIntent, String resolvedType, String callingPackage,
6798            Bundle verificationBundle, int userId) {
6799        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6800                new InstantAppRequest(responseObj, origIntent, resolvedType,
6801                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6802        mHandler.sendMessage(msg);
6803    }
6804
6805    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6806            int flags, List<ResolveInfo> query, int userId) {
6807        if (query != null) {
6808            final int N = query.size();
6809            if (N == 1) {
6810                return query.get(0);
6811            } else if (N > 1) {
6812                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6813                // If there is more than one activity with the same priority,
6814                // then let the user decide between them.
6815                ResolveInfo r0 = query.get(0);
6816                ResolveInfo r1 = query.get(1);
6817                if (DEBUG_INTENT_MATCHING || debug) {
6818                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6819                            + r1.activityInfo.name + "=" + r1.priority);
6820                }
6821                // If the first activity has a higher priority, or a different
6822                // default, then it is always desirable to pick it.
6823                if (r0.priority != r1.priority
6824                        || r0.preferredOrder != r1.preferredOrder
6825                        || r0.isDefault != r1.isDefault) {
6826                    return query.get(0);
6827                }
6828                // If we have saved a preference for a preferred activity for
6829                // this Intent, use that.
6830                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6831                        flags, query, r0.priority, true, false, debug, userId);
6832                if (ri != null) {
6833                    return ri;
6834                }
6835                // If we have an ephemeral app, use it
6836                for (int i = 0; i < N; i++) {
6837                    ri = query.get(i);
6838                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6839                        final String packageName = ri.activityInfo.packageName;
6840                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6841                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6842                        final int status = (int)(packedStatus >> 32);
6843                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6844                            return ri;
6845                        }
6846                    }
6847                }
6848                ri = new ResolveInfo(mResolveInfo);
6849                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6850                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6851                // If all of the options come from the same package, show the application's
6852                // label and icon instead of the generic resolver's.
6853                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6854                // and then throw away the ResolveInfo itself, meaning that the caller loses
6855                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6856                // a fallback for this case; we only set the target package's resources on
6857                // the ResolveInfo, not the ActivityInfo.
6858                final String intentPackage = intent.getPackage();
6859                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6860                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6861                    ri.resolvePackageName = intentPackage;
6862                    if (userNeedsBadging(userId)) {
6863                        ri.noResourceId = true;
6864                    } else {
6865                        ri.icon = appi.icon;
6866                    }
6867                    ri.iconResourceId = appi.icon;
6868                    ri.labelRes = appi.labelRes;
6869                }
6870                ri.activityInfo.applicationInfo = new ApplicationInfo(
6871                        ri.activityInfo.applicationInfo);
6872                if (userId != 0) {
6873                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6874                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6875                }
6876                // Make sure that the resolver is displayable in car mode
6877                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6878                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6879                return ri;
6880            }
6881        }
6882        return null;
6883    }
6884
6885    /**
6886     * Return true if the given list is not empty and all of its contents have
6887     * an activityInfo with the given package name.
6888     */
6889    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6890        if (ArrayUtils.isEmpty(list)) {
6891            return false;
6892        }
6893        for (int i = 0, N = list.size(); i < N; i++) {
6894            final ResolveInfo ri = list.get(i);
6895            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6896            if (ai == null || !packageName.equals(ai.packageName)) {
6897                return false;
6898            }
6899        }
6900        return true;
6901    }
6902
6903    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6904            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6905        final int N = query.size();
6906        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6907                .get(userId);
6908        // Get the list of persistent preferred activities that handle the intent
6909        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6910        List<PersistentPreferredActivity> pprefs = ppir != null
6911                ? ppir.queryIntent(intent, resolvedType,
6912                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6913                        userId)
6914                : null;
6915        if (pprefs != null && pprefs.size() > 0) {
6916            final int M = pprefs.size();
6917            for (int i=0; i<M; i++) {
6918                final PersistentPreferredActivity ppa = pprefs.get(i);
6919                if (DEBUG_PREFERRED || debug) {
6920                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6921                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6922                            + "\n  component=" + ppa.mComponent);
6923                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6924                }
6925                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6926                        flags | MATCH_DISABLED_COMPONENTS, userId);
6927                if (DEBUG_PREFERRED || debug) {
6928                    Slog.v(TAG, "Found persistent preferred activity:");
6929                    if (ai != null) {
6930                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6931                    } else {
6932                        Slog.v(TAG, "  null");
6933                    }
6934                }
6935                if (ai == null) {
6936                    // This previously registered persistent preferred activity
6937                    // component is no longer known. Ignore it and do NOT remove it.
6938                    continue;
6939                }
6940                for (int j=0; j<N; j++) {
6941                    final ResolveInfo ri = query.get(j);
6942                    if (!ri.activityInfo.applicationInfo.packageName
6943                            .equals(ai.applicationInfo.packageName)) {
6944                        continue;
6945                    }
6946                    if (!ri.activityInfo.name.equals(ai.name)) {
6947                        continue;
6948                    }
6949                    //  Found a persistent preference that can handle the intent.
6950                    if (DEBUG_PREFERRED || debug) {
6951                        Slog.v(TAG, "Returning persistent preferred activity: " +
6952                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6953                    }
6954                    return ri;
6955                }
6956            }
6957        }
6958        return null;
6959    }
6960
6961    // TODO: handle preferred activities missing while user has amnesia
6962    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6963            List<ResolveInfo> query, int priority, boolean always,
6964            boolean removeMatches, boolean debug, int userId) {
6965        if (!sUserManager.exists(userId)) return null;
6966        final int callingUid = Binder.getCallingUid();
6967        flags = updateFlagsForResolve(
6968                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6969        intent = updateIntentForResolve(intent);
6970        // writer
6971        synchronized (mPackages) {
6972            // Try to find a matching persistent preferred activity.
6973            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6974                    debug, userId);
6975
6976            // If a persistent preferred activity matched, use it.
6977            if (pri != null) {
6978                return pri;
6979            }
6980
6981            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6982            // Get the list of preferred activities that handle the intent
6983            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6984            List<PreferredActivity> prefs = pir != null
6985                    ? pir.queryIntent(intent, resolvedType,
6986                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6987                            userId)
6988                    : null;
6989            if (prefs != null && prefs.size() > 0) {
6990                boolean changed = false;
6991                try {
6992                    // First figure out how good the original match set is.
6993                    // We will only allow preferred activities that came
6994                    // from the same match quality.
6995                    int match = 0;
6996
6997                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6998
6999                    final int N = query.size();
7000                    for (int j=0; j<N; j++) {
7001                        final ResolveInfo ri = query.get(j);
7002                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
7003                                + ": 0x" + Integer.toHexString(match));
7004                        if (ri.match > match) {
7005                            match = ri.match;
7006                        }
7007                    }
7008
7009                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
7010                            + Integer.toHexString(match));
7011
7012                    match &= IntentFilter.MATCH_CATEGORY_MASK;
7013                    final int M = prefs.size();
7014                    for (int i=0; i<M; i++) {
7015                        final PreferredActivity pa = prefs.get(i);
7016                        if (DEBUG_PREFERRED || debug) {
7017                            Slog.v(TAG, "Checking PreferredActivity ds="
7018                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
7019                                    + "\n  component=" + pa.mPref.mComponent);
7020                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7021                        }
7022                        if (pa.mPref.mMatch != match) {
7023                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
7024                                    + Integer.toHexString(pa.mPref.mMatch));
7025                            continue;
7026                        }
7027                        // If it's not an "always" type preferred activity and that's what we're
7028                        // looking for, skip it.
7029                        if (always && !pa.mPref.mAlways) {
7030                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7031                            continue;
7032                        }
7033                        final ActivityInfo ai = getActivityInfo(
7034                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7035                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7036                                userId);
7037                        if (DEBUG_PREFERRED || debug) {
7038                            Slog.v(TAG, "Found preferred activity:");
7039                            if (ai != null) {
7040                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7041                            } else {
7042                                Slog.v(TAG, "  null");
7043                            }
7044                        }
7045                        if (ai == null) {
7046                            // This previously registered preferred activity
7047                            // component is no longer known.  Most likely an update
7048                            // to the app was installed and in the new version this
7049                            // component no longer exists.  Clean it up by removing
7050                            // it from the preferred activities list, and skip it.
7051                            Slog.w(TAG, "Removing dangling preferred activity: "
7052                                    + pa.mPref.mComponent);
7053                            pir.removeFilter(pa);
7054                            changed = true;
7055                            continue;
7056                        }
7057                        for (int j=0; j<N; j++) {
7058                            final ResolveInfo ri = query.get(j);
7059                            if (!ri.activityInfo.applicationInfo.packageName
7060                                    .equals(ai.applicationInfo.packageName)) {
7061                                continue;
7062                            }
7063                            if (!ri.activityInfo.name.equals(ai.name)) {
7064                                continue;
7065                            }
7066
7067                            if (removeMatches) {
7068                                pir.removeFilter(pa);
7069                                changed = true;
7070                                if (DEBUG_PREFERRED) {
7071                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7072                                }
7073                                break;
7074                            }
7075
7076                            // Okay we found a previously set preferred or last chosen app.
7077                            // If the result set is different from when this
7078                            // was created, and is not a subset of the preferred set, we need to
7079                            // clear it and re-ask the user their preference, if we're looking for
7080                            // an "always" type entry.
7081                            if (always && !pa.mPref.sameSet(query)) {
7082                                if (pa.mPref.isSuperset(query)) {
7083                                    // some components of the set are no longer present in
7084                                    // the query, but the preferred activity can still be reused
7085                                    if (DEBUG_PREFERRED) {
7086                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7087                                                + " still valid as only non-preferred components"
7088                                                + " were removed for " + intent + " type "
7089                                                + resolvedType);
7090                                    }
7091                                    // remove obsolete components and re-add the up-to-date filter
7092                                    PreferredActivity freshPa = new PreferredActivity(pa,
7093                                            pa.mPref.mMatch,
7094                                            pa.mPref.discardObsoleteComponents(query),
7095                                            pa.mPref.mComponent,
7096                                            pa.mPref.mAlways);
7097                                    pir.removeFilter(pa);
7098                                    pir.addFilter(freshPa);
7099                                    changed = true;
7100                                } else {
7101                                    Slog.i(TAG,
7102                                            "Result set changed, dropping preferred activity for "
7103                                                    + intent + " type " + resolvedType);
7104                                    if (DEBUG_PREFERRED) {
7105                                        Slog.v(TAG, "Removing preferred activity since set changed "
7106                                                + pa.mPref.mComponent);
7107                                    }
7108                                    pir.removeFilter(pa);
7109                                    // Re-add the filter as a "last chosen" entry (!always)
7110                                    PreferredActivity lastChosen = new PreferredActivity(
7111                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7112                                    pir.addFilter(lastChosen);
7113                                    changed = true;
7114                                    return null;
7115                                }
7116                            }
7117
7118                            // Yay! Either the set matched or we're looking for the last chosen
7119                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7120                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7121                            return ri;
7122                        }
7123                    }
7124                } finally {
7125                    if (changed) {
7126                        if (DEBUG_PREFERRED) {
7127                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7128                        }
7129                        scheduleWritePackageRestrictionsLocked(userId);
7130                    }
7131                }
7132            }
7133        }
7134        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7135        return null;
7136    }
7137
7138    /*
7139     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7140     */
7141    @Override
7142    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7143            int targetUserId) {
7144        mContext.enforceCallingOrSelfPermission(
7145                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7146        List<CrossProfileIntentFilter> matches =
7147                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7148        if (matches != null) {
7149            int size = matches.size();
7150            for (int i = 0; i < size; i++) {
7151                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7152            }
7153        }
7154        if (hasWebURI(intent)) {
7155            // cross-profile app linking works only towards the parent.
7156            final int callingUid = Binder.getCallingUid();
7157            final UserInfo parent = getProfileParent(sourceUserId);
7158            synchronized(mPackages) {
7159                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7160                        false /*includeInstantApps*/);
7161                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7162                        intent, resolvedType, flags, sourceUserId, parent.id);
7163                return xpDomainInfo != null;
7164            }
7165        }
7166        return false;
7167    }
7168
7169    private UserInfo getProfileParent(int userId) {
7170        final long identity = Binder.clearCallingIdentity();
7171        try {
7172            return sUserManager.getProfileParent(userId);
7173        } finally {
7174            Binder.restoreCallingIdentity(identity);
7175        }
7176    }
7177
7178    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7179            String resolvedType, int userId) {
7180        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7181        if (resolver != null) {
7182            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7183        }
7184        return null;
7185    }
7186
7187    @Override
7188    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7189            String resolvedType, int flags, int userId) {
7190        try {
7191            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7192
7193            return new ParceledListSlice<>(
7194                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7195        } finally {
7196            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7197        }
7198    }
7199
7200    /**
7201     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7202     * instant, returns {@code null}.
7203     */
7204    private String getInstantAppPackageName(int callingUid) {
7205        synchronized (mPackages) {
7206            // If the caller is an isolated app use the owner's uid for the lookup.
7207            if (Process.isIsolated(callingUid)) {
7208                callingUid = mIsolatedOwners.get(callingUid);
7209            }
7210            final int appId = UserHandle.getAppId(callingUid);
7211            final Object obj = mSettings.getUserIdLPr(appId);
7212            if (obj instanceof PackageSetting) {
7213                final PackageSetting ps = (PackageSetting) obj;
7214                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7215                return isInstantApp ? ps.pkg.packageName : null;
7216            }
7217        }
7218        return null;
7219    }
7220
7221    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7222            String resolvedType, int flags, int userId) {
7223        return queryIntentActivitiesInternal(
7224                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7225                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7226    }
7227
7228    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7229            String resolvedType, int flags, int filterCallingUid, int userId,
7230            boolean resolveForStart, boolean allowDynamicSplits) {
7231        if (!sUserManager.exists(userId)) return Collections.emptyList();
7232        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7233        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7234                false /* requireFullPermission */, false /* checkShell */,
7235                "query intent activities");
7236        final String pkgName = intent.getPackage();
7237        ComponentName comp = intent.getComponent();
7238        if (comp == null) {
7239            if (intent.getSelector() != null) {
7240                intent = intent.getSelector();
7241                comp = intent.getComponent();
7242            }
7243        }
7244
7245        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7246                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7247        if (comp != null) {
7248            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7249            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7250            if (ai != null) {
7251                // When specifying an explicit component, we prevent the activity from being
7252                // used when either 1) the calling package is normal and the activity is within
7253                // an ephemeral application or 2) the calling package is ephemeral and the
7254                // activity is not visible to ephemeral applications.
7255                final boolean matchInstantApp =
7256                        (flags & PackageManager.MATCH_INSTANT) != 0;
7257                final boolean matchVisibleToInstantAppOnly =
7258                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7259                final boolean matchExplicitlyVisibleOnly =
7260                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7261                final boolean isCallerInstantApp =
7262                        instantAppPkgName != null;
7263                final boolean isTargetSameInstantApp =
7264                        comp.getPackageName().equals(instantAppPkgName);
7265                final boolean isTargetInstantApp =
7266                        (ai.applicationInfo.privateFlags
7267                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7268                final boolean isTargetVisibleToInstantApp =
7269                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7270                final boolean isTargetExplicitlyVisibleToInstantApp =
7271                        isTargetVisibleToInstantApp
7272                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7273                final boolean isTargetHiddenFromInstantApp =
7274                        !isTargetVisibleToInstantApp
7275                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7276                final boolean blockResolution =
7277                        !isTargetSameInstantApp
7278                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7279                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7280                                        && isTargetHiddenFromInstantApp));
7281                if (!blockResolution) {
7282                    final ResolveInfo ri = new ResolveInfo();
7283                    ri.activityInfo = ai;
7284                    list.add(ri);
7285                }
7286            }
7287            return applyPostResolutionFilter(
7288                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7289        }
7290
7291        // reader
7292        boolean sortResult = false;
7293        boolean addEphemeral = false;
7294        List<ResolveInfo> result;
7295        final boolean ephemeralDisabled = isEphemeralDisabled();
7296        synchronized (mPackages) {
7297            if (pkgName == null) {
7298                List<CrossProfileIntentFilter> matchingFilters =
7299                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7300                // Check for results that need to skip the current profile.
7301                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7302                        resolvedType, flags, userId);
7303                if (xpResolveInfo != null) {
7304                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7305                    xpResult.add(xpResolveInfo);
7306                    return applyPostResolutionFilter(
7307                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7308                            allowDynamicSplits, filterCallingUid, userId);
7309                }
7310
7311                // Check for results in the current profile.
7312                result = filterIfNotSystemUser(mActivities.queryIntent(
7313                        intent, resolvedType, flags, userId), userId);
7314                addEphemeral = !ephemeralDisabled
7315                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7316                // Check for cross profile results.
7317                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7318                xpResolveInfo = queryCrossProfileIntents(
7319                        matchingFilters, intent, resolvedType, flags, userId,
7320                        hasNonNegativePriorityResult);
7321                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7322                    boolean isVisibleToUser = filterIfNotSystemUser(
7323                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7324                    if (isVisibleToUser) {
7325                        result.add(xpResolveInfo);
7326                        sortResult = true;
7327                    }
7328                }
7329                if (hasWebURI(intent)) {
7330                    CrossProfileDomainInfo xpDomainInfo = null;
7331                    final UserInfo parent = getProfileParent(userId);
7332                    if (parent != null) {
7333                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7334                                flags, userId, parent.id);
7335                    }
7336                    if (xpDomainInfo != null) {
7337                        if (xpResolveInfo != null) {
7338                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7339                            // in the result.
7340                            result.remove(xpResolveInfo);
7341                        }
7342                        if (result.size() == 0 && !addEphemeral) {
7343                            // No result in current profile, but found candidate in parent user.
7344                            // And we are not going to add emphemeral app, so we can return the
7345                            // result straight away.
7346                            result.add(xpDomainInfo.resolveInfo);
7347                            return applyPostResolutionFilter(result, instantAppPkgName,
7348                                    allowDynamicSplits, filterCallingUid, userId);
7349                        }
7350                    } else if (result.size() <= 1 && !addEphemeral) {
7351                        // No result in parent user and <= 1 result in current profile, and we
7352                        // are not going to add emphemeral app, so we can return the result without
7353                        // further processing.
7354                        return applyPostResolutionFilter(result, instantAppPkgName,
7355                                allowDynamicSplits, filterCallingUid, userId);
7356                    }
7357                    // We have more than one candidate (combining results from current and parent
7358                    // profile), so we need filtering and sorting.
7359                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7360                            intent, flags, result, xpDomainInfo, userId);
7361                    sortResult = true;
7362                }
7363            } else {
7364                final PackageParser.Package pkg = mPackages.get(pkgName);
7365                result = null;
7366                if (pkg != null) {
7367                    result = filterIfNotSystemUser(
7368                            mActivities.queryIntentForPackage(
7369                                    intent, resolvedType, flags, pkg.activities, userId),
7370                            userId);
7371                }
7372                if (result == null || result.size() == 0) {
7373                    // the caller wants to resolve for a particular package; however, there
7374                    // were no installed results, so, try to find an ephemeral result
7375                    addEphemeral = !ephemeralDisabled
7376                            && isInstantAppAllowed(
7377                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7378                    if (result == null) {
7379                        result = new ArrayList<>();
7380                    }
7381                }
7382            }
7383        }
7384        if (addEphemeral) {
7385            result = maybeAddInstantAppInstaller(
7386                    result, intent, resolvedType, flags, userId, resolveForStart);
7387        }
7388        if (sortResult) {
7389            Collections.sort(result, mResolvePrioritySorter);
7390        }
7391        return applyPostResolutionFilter(
7392                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7393    }
7394
7395    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7396            String resolvedType, int flags, int userId, boolean resolveForStart) {
7397        // first, check to see if we've got an instant app already installed
7398        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7399        ResolveInfo localInstantApp = null;
7400        boolean blockResolution = false;
7401        if (!alreadyResolvedLocally) {
7402            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7403                    flags
7404                        | PackageManager.GET_RESOLVED_FILTER
7405                        | PackageManager.MATCH_INSTANT
7406                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7407                    userId);
7408            for (int i = instantApps.size() - 1; i >= 0; --i) {
7409                final ResolveInfo info = instantApps.get(i);
7410                final String packageName = info.activityInfo.packageName;
7411                final PackageSetting ps = mSettings.mPackages.get(packageName);
7412                if (ps.getInstantApp(userId)) {
7413                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7414                    final int status = (int)(packedStatus >> 32);
7415                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7416                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7417                        // there's a local instant application installed, but, the user has
7418                        // chosen to never use it; skip resolution and don't acknowledge
7419                        // an instant application is even available
7420                        if (DEBUG_EPHEMERAL) {
7421                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7422                        }
7423                        blockResolution = true;
7424                        break;
7425                    } else {
7426                        // we have a locally installed instant application; skip resolution
7427                        // but acknowledge there's an instant application available
7428                        if (DEBUG_EPHEMERAL) {
7429                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7430                        }
7431                        localInstantApp = info;
7432                        break;
7433                    }
7434                }
7435            }
7436        }
7437        // no app installed, let's see if one's available
7438        AuxiliaryResolveInfo auxiliaryResponse = null;
7439        if (!blockResolution) {
7440            if (localInstantApp == null) {
7441                // we don't have an instant app locally, resolve externally
7442                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7443                final InstantAppRequest requestObject = new InstantAppRequest(
7444                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7445                        null /*callingPackage*/, userId, null /*verificationBundle*/,
7446                        resolveForStart);
7447                auxiliaryResponse =
7448                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7449                                mContext, mInstantAppResolverConnection, requestObject);
7450                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7451            } else {
7452                // we have an instant application locally, but, we can't admit that since
7453                // callers shouldn't be able to determine prior browsing. create a dummy
7454                // auxiliary response so the downstream code behaves as if there's an
7455                // instant application available externally. when it comes time to start
7456                // the instant application, we'll do the right thing.
7457                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7458                auxiliaryResponse = new AuxiliaryResolveInfo(
7459                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7460                        ai.versionCode, null /*failureIntent*/);
7461            }
7462        }
7463        if (auxiliaryResponse != null) {
7464            if (DEBUG_EPHEMERAL) {
7465                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7466            }
7467            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7468            final PackageSetting ps =
7469                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7470            if (ps != null) {
7471                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7472                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7473                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7474                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7475                // make sure this resolver is the default
7476                ephemeralInstaller.isDefault = true;
7477                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7478                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7479                // add a non-generic filter
7480                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7481                ephemeralInstaller.filter.addDataPath(
7482                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7483                ephemeralInstaller.isInstantAppAvailable = true;
7484                result.add(ephemeralInstaller);
7485            }
7486        }
7487        return result;
7488    }
7489
7490    private static class CrossProfileDomainInfo {
7491        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7492        ResolveInfo resolveInfo;
7493        /* Best domain verification status of the activities found in the other profile */
7494        int bestDomainVerificationStatus;
7495    }
7496
7497    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7498            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7499        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7500                sourceUserId)) {
7501            return null;
7502        }
7503        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7504                resolvedType, flags, parentUserId);
7505
7506        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7507            return null;
7508        }
7509        CrossProfileDomainInfo result = null;
7510        int size = resultTargetUser.size();
7511        for (int i = 0; i < size; i++) {
7512            ResolveInfo riTargetUser = resultTargetUser.get(i);
7513            // Intent filter verification is only for filters that specify a host. So don't return
7514            // those that handle all web uris.
7515            if (riTargetUser.handleAllWebDataURI) {
7516                continue;
7517            }
7518            String packageName = riTargetUser.activityInfo.packageName;
7519            PackageSetting ps = mSettings.mPackages.get(packageName);
7520            if (ps == null) {
7521                continue;
7522            }
7523            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7524            int status = (int)(verificationState >> 32);
7525            if (result == null) {
7526                result = new CrossProfileDomainInfo();
7527                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7528                        sourceUserId, parentUserId);
7529                result.bestDomainVerificationStatus = status;
7530            } else {
7531                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7532                        result.bestDomainVerificationStatus);
7533            }
7534        }
7535        // Don't consider matches with status NEVER across profiles.
7536        if (result != null && result.bestDomainVerificationStatus
7537                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7538            return null;
7539        }
7540        return result;
7541    }
7542
7543    /**
7544     * Verification statuses are ordered from the worse to the best, except for
7545     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7546     */
7547    private int bestDomainVerificationStatus(int status1, int status2) {
7548        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7549            return status2;
7550        }
7551        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7552            return status1;
7553        }
7554        return (int) MathUtils.max(status1, status2);
7555    }
7556
7557    private boolean isUserEnabled(int userId) {
7558        long callingId = Binder.clearCallingIdentity();
7559        try {
7560            UserInfo userInfo = sUserManager.getUserInfo(userId);
7561            return userInfo != null && userInfo.isEnabled();
7562        } finally {
7563            Binder.restoreCallingIdentity(callingId);
7564        }
7565    }
7566
7567    /**
7568     * Filter out activities with systemUserOnly flag set, when current user is not System.
7569     *
7570     * @return filtered list
7571     */
7572    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7573        if (userId == UserHandle.USER_SYSTEM) {
7574            return resolveInfos;
7575        }
7576        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7577            ResolveInfo info = resolveInfos.get(i);
7578            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7579                resolveInfos.remove(i);
7580            }
7581        }
7582        return resolveInfos;
7583    }
7584
7585    /**
7586     * Filters out ephemeral activities.
7587     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7588     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7589     *
7590     * @param resolveInfos The pre-filtered list of resolved activities
7591     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7592     *          is performed.
7593     * @return A filtered list of resolved activities.
7594     */
7595    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7596            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7597        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7598            final ResolveInfo info = resolveInfos.get(i);
7599            // allow activities that are defined in the provided package
7600            if (allowDynamicSplits
7601                    && info.activityInfo.splitName != null
7602                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7603                            info.activityInfo.splitName)) {
7604                // requested activity is defined in a split that hasn't been installed yet.
7605                // add the installer to the resolve list
7606                if (DEBUG_INSTALL) {
7607                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7608                }
7609                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7610                final ComponentName installFailureActivity = findInstallFailureActivity(
7611                        info.activityInfo.packageName,  filterCallingUid, userId);
7612                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7613                        info.activityInfo.packageName, info.activityInfo.splitName,
7614                        installFailureActivity,
7615                        info.activityInfo.applicationInfo.versionCode,
7616                        null /*failureIntent*/);
7617                // make sure this resolver is the default
7618                installerInfo.isDefault = true;
7619                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7620                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7621                // add a non-generic filter
7622                installerInfo.filter = new IntentFilter();
7623                // load resources from the correct package
7624                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7625                resolveInfos.set(i, installerInfo);
7626                continue;
7627            }
7628            // caller is a full app, don't need to apply any other filtering
7629            if (ephemeralPkgName == null) {
7630                continue;
7631            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7632                // caller is same app; don't need to apply any other filtering
7633                continue;
7634            }
7635            // allow activities that have been explicitly exposed to ephemeral apps
7636            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7637            if (!isEphemeralApp
7638                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7639                continue;
7640            }
7641            resolveInfos.remove(i);
7642        }
7643        return resolveInfos;
7644    }
7645
7646    /**
7647     * Returns the activity component that can handle install failures.
7648     * <p>By default, the instant application installer handles failures. However, an
7649     * application may want to handle failures on its own. Applications do this by
7650     * creating an activity with an intent filter that handles the action
7651     * {@link Intent#ACTION_INSTALL_FAILURE}.
7652     */
7653    private @Nullable ComponentName findInstallFailureActivity(
7654            String packageName, int filterCallingUid, int userId) {
7655        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7656        failureActivityIntent.setPackage(packageName);
7657        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7658        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7659                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7660                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7661        final int NR = result.size();
7662        if (NR > 0) {
7663            for (int i = 0; i < NR; i++) {
7664                final ResolveInfo info = result.get(i);
7665                if (info.activityInfo.splitName != null) {
7666                    continue;
7667                }
7668                return new ComponentName(packageName, info.activityInfo.name);
7669            }
7670        }
7671        return null;
7672    }
7673
7674    /**
7675     * @param resolveInfos list of resolve infos in descending priority order
7676     * @return if the list contains a resolve info with non-negative priority
7677     */
7678    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7679        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7680    }
7681
7682    private static boolean hasWebURI(Intent intent) {
7683        if (intent.getData() == null) {
7684            return false;
7685        }
7686        final String scheme = intent.getScheme();
7687        if (TextUtils.isEmpty(scheme)) {
7688            return false;
7689        }
7690        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7691    }
7692
7693    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7694            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7695            int userId) {
7696        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7697
7698        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7699            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7700                    candidates.size());
7701        }
7702
7703        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7704        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7705        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7706        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7707        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7708        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7709
7710        synchronized (mPackages) {
7711            final int count = candidates.size();
7712            // First, try to use linked apps. Partition the candidates into four lists:
7713            // one for the final results, one for the "do not use ever", one for "undefined status"
7714            // and finally one for "browser app type".
7715            for (int n=0; n<count; n++) {
7716                ResolveInfo info = candidates.get(n);
7717                String packageName = info.activityInfo.packageName;
7718                PackageSetting ps = mSettings.mPackages.get(packageName);
7719                if (ps != null) {
7720                    // Add to the special match all list (Browser use case)
7721                    if (info.handleAllWebDataURI) {
7722                        matchAllList.add(info);
7723                        continue;
7724                    }
7725                    // Try to get the status from User settings first
7726                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7727                    int status = (int)(packedStatus >> 32);
7728                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7729                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7730                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7731                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7732                                    + " : linkgen=" + linkGeneration);
7733                        }
7734                        // Use link-enabled generation as preferredOrder, i.e.
7735                        // prefer newly-enabled over earlier-enabled.
7736                        info.preferredOrder = linkGeneration;
7737                        alwaysList.add(info);
7738                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7739                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7740                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7741                        }
7742                        neverList.add(info);
7743                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7744                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7745                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7746                        }
7747                        alwaysAskList.add(info);
7748                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7749                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7750                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7751                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7752                        }
7753                        undefinedList.add(info);
7754                    }
7755                }
7756            }
7757
7758            // We'll want to include browser possibilities in a few cases
7759            boolean includeBrowser = false;
7760
7761            // First try to add the "always" resolution(s) for the current user, if any
7762            if (alwaysList.size() > 0) {
7763                result.addAll(alwaysList);
7764            } else {
7765                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7766                result.addAll(undefinedList);
7767                // Maybe add one for the other profile.
7768                if (xpDomainInfo != null && (
7769                        xpDomainInfo.bestDomainVerificationStatus
7770                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7771                    result.add(xpDomainInfo.resolveInfo);
7772                }
7773                includeBrowser = true;
7774            }
7775
7776            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7777            // If there were 'always' entries their preferred order has been set, so we also
7778            // back that off to make the alternatives equivalent
7779            if (alwaysAskList.size() > 0) {
7780                for (ResolveInfo i : result) {
7781                    i.preferredOrder = 0;
7782                }
7783                result.addAll(alwaysAskList);
7784                includeBrowser = true;
7785            }
7786
7787            if (includeBrowser) {
7788                // Also add browsers (all of them or only the default one)
7789                if (DEBUG_DOMAIN_VERIFICATION) {
7790                    Slog.v(TAG, "   ...including browsers in candidate set");
7791                }
7792                if ((matchFlags & MATCH_ALL) != 0) {
7793                    result.addAll(matchAllList);
7794                } else {
7795                    // Browser/generic handling case.  If there's a default browser, go straight
7796                    // to that (but only if there is no other higher-priority match).
7797                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7798                    int maxMatchPrio = 0;
7799                    ResolveInfo defaultBrowserMatch = null;
7800                    final int numCandidates = matchAllList.size();
7801                    for (int n = 0; n < numCandidates; n++) {
7802                        ResolveInfo info = matchAllList.get(n);
7803                        // track the highest overall match priority...
7804                        if (info.priority > maxMatchPrio) {
7805                            maxMatchPrio = info.priority;
7806                        }
7807                        // ...and the highest-priority default browser match
7808                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7809                            if (defaultBrowserMatch == null
7810                                    || (defaultBrowserMatch.priority < info.priority)) {
7811                                if (debug) {
7812                                    Slog.v(TAG, "Considering default browser match " + info);
7813                                }
7814                                defaultBrowserMatch = info;
7815                            }
7816                        }
7817                    }
7818                    if (defaultBrowserMatch != null
7819                            && defaultBrowserMatch.priority >= maxMatchPrio
7820                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7821                    {
7822                        if (debug) {
7823                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7824                        }
7825                        result.add(defaultBrowserMatch);
7826                    } else {
7827                        result.addAll(matchAllList);
7828                    }
7829                }
7830
7831                // If there is nothing selected, add all candidates and remove the ones that the user
7832                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7833                if (result.size() == 0) {
7834                    result.addAll(candidates);
7835                    result.removeAll(neverList);
7836                }
7837            }
7838        }
7839        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7840            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7841                    result.size());
7842            for (ResolveInfo info : result) {
7843                Slog.v(TAG, "  + " + info.activityInfo);
7844            }
7845        }
7846        return result;
7847    }
7848
7849    // Returns a packed value as a long:
7850    //
7851    // high 'int'-sized word: link status: undefined/ask/never/always.
7852    // low 'int'-sized word: relative priority among 'always' results.
7853    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7854        long result = ps.getDomainVerificationStatusForUser(userId);
7855        // if none available, get the master status
7856        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7857            if (ps.getIntentFilterVerificationInfo() != null) {
7858                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7859            }
7860        }
7861        return result;
7862    }
7863
7864    private ResolveInfo querySkipCurrentProfileIntents(
7865            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7866            int flags, int sourceUserId) {
7867        if (matchingFilters != null) {
7868            int size = matchingFilters.size();
7869            for (int i = 0; i < size; i ++) {
7870                CrossProfileIntentFilter filter = matchingFilters.get(i);
7871                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7872                    // Checking if there are activities in the target user that can handle the
7873                    // intent.
7874                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7875                            resolvedType, flags, sourceUserId);
7876                    if (resolveInfo != null) {
7877                        return resolveInfo;
7878                    }
7879                }
7880            }
7881        }
7882        return null;
7883    }
7884
7885    // Return matching ResolveInfo in target user if any.
7886    private ResolveInfo queryCrossProfileIntents(
7887            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7888            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7889        if (matchingFilters != null) {
7890            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7891            // match the same intent. For performance reasons, it is better not to
7892            // run queryIntent twice for the same userId
7893            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7894            int size = matchingFilters.size();
7895            for (int i = 0; i < size; i++) {
7896                CrossProfileIntentFilter filter = matchingFilters.get(i);
7897                int targetUserId = filter.getTargetUserId();
7898                boolean skipCurrentProfile =
7899                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7900                boolean skipCurrentProfileIfNoMatchFound =
7901                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7902                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7903                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7904                    // Checking if there are activities in the target user that can handle the
7905                    // intent.
7906                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7907                            resolvedType, flags, sourceUserId);
7908                    if (resolveInfo != null) return resolveInfo;
7909                    alreadyTriedUserIds.put(targetUserId, true);
7910                }
7911            }
7912        }
7913        return null;
7914    }
7915
7916    /**
7917     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7918     * will forward the intent to the filter's target user.
7919     * Otherwise, returns null.
7920     */
7921    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7922            String resolvedType, int flags, int sourceUserId) {
7923        int targetUserId = filter.getTargetUserId();
7924        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7925                resolvedType, flags, targetUserId);
7926        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7927            // If all the matches in the target profile are suspended, return null.
7928            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7929                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7930                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7931                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7932                            targetUserId);
7933                }
7934            }
7935        }
7936        return null;
7937    }
7938
7939    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7940            int sourceUserId, int targetUserId) {
7941        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7942        long ident = Binder.clearCallingIdentity();
7943        boolean targetIsProfile;
7944        try {
7945            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7946        } finally {
7947            Binder.restoreCallingIdentity(ident);
7948        }
7949        String className;
7950        if (targetIsProfile) {
7951            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7952        } else {
7953            className = FORWARD_INTENT_TO_PARENT;
7954        }
7955        ComponentName forwardingActivityComponentName = new ComponentName(
7956                mAndroidApplication.packageName, className);
7957        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7958                sourceUserId);
7959        if (!targetIsProfile) {
7960            forwardingActivityInfo.showUserIcon = targetUserId;
7961            forwardingResolveInfo.noResourceId = true;
7962        }
7963        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7964        forwardingResolveInfo.priority = 0;
7965        forwardingResolveInfo.preferredOrder = 0;
7966        forwardingResolveInfo.match = 0;
7967        forwardingResolveInfo.isDefault = true;
7968        forwardingResolveInfo.filter = filter;
7969        forwardingResolveInfo.targetUserId = targetUserId;
7970        return forwardingResolveInfo;
7971    }
7972
7973    @Override
7974    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7975            Intent[] specifics, String[] specificTypes, Intent intent,
7976            String resolvedType, int flags, int userId) {
7977        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7978                specificTypes, intent, resolvedType, flags, userId));
7979    }
7980
7981    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7982            Intent[] specifics, String[] specificTypes, Intent intent,
7983            String resolvedType, int flags, int userId) {
7984        if (!sUserManager.exists(userId)) return Collections.emptyList();
7985        final int callingUid = Binder.getCallingUid();
7986        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7987                false /*includeInstantApps*/);
7988        enforceCrossUserPermission(callingUid, userId,
7989                false /*requireFullPermission*/, false /*checkShell*/,
7990                "query intent activity options");
7991        final String resultsAction = intent.getAction();
7992
7993        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7994                | PackageManager.GET_RESOLVED_FILTER, userId);
7995
7996        if (DEBUG_INTENT_MATCHING) {
7997            Log.v(TAG, "Query " + intent + ": " + results);
7998        }
7999
8000        int specificsPos = 0;
8001        int N;
8002
8003        // todo: note that the algorithm used here is O(N^2).  This
8004        // isn't a problem in our current environment, but if we start running
8005        // into situations where we have more than 5 or 10 matches then this
8006        // should probably be changed to something smarter...
8007
8008        // First we go through and resolve each of the specific items
8009        // that were supplied, taking care of removing any corresponding
8010        // duplicate items in the generic resolve list.
8011        if (specifics != null) {
8012            for (int i=0; i<specifics.length; i++) {
8013                final Intent sintent = specifics[i];
8014                if (sintent == null) {
8015                    continue;
8016                }
8017
8018                if (DEBUG_INTENT_MATCHING) {
8019                    Log.v(TAG, "Specific #" + i + ": " + sintent);
8020                }
8021
8022                String action = sintent.getAction();
8023                if (resultsAction != null && resultsAction.equals(action)) {
8024                    // If this action was explicitly requested, then don't
8025                    // remove things that have it.
8026                    action = null;
8027                }
8028
8029                ResolveInfo ri = null;
8030                ActivityInfo ai = null;
8031
8032                ComponentName comp = sintent.getComponent();
8033                if (comp == null) {
8034                    ri = resolveIntent(
8035                        sintent,
8036                        specificTypes != null ? specificTypes[i] : null,
8037                            flags, userId);
8038                    if (ri == null) {
8039                        continue;
8040                    }
8041                    if (ri == mResolveInfo) {
8042                        // ACK!  Must do something better with this.
8043                    }
8044                    ai = ri.activityInfo;
8045                    comp = new ComponentName(ai.applicationInfo.packageName,
8046                            ai.name);
8047                } else {
8048                    ai = getActivityInfo(comp, flags, userId);
8049                    if (ai == null) {
8050                        continue;
8051                    }
8052                }
8053
8054                // Look for any generic query activities that are duplicates
8055                // of this specific one, and remove them from the results.
8056                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8057                N = results.size();
8058                int j;
8059                for (j=specificsPos; j<N; j++) {
8060                    ResolveInfo sri = results.get(j);
8061                    if ((sri.activityInfo.name.equals(comp.getClassName())
8062                            && sri.activityInfo.applicationInfo.packageName.equals(
8063                                    comp.getPackageName()))
8064                        || (action != null && sri.filter.matchAction(action))) {
8065                        results.remove(j);
8066                        if (DEBUG_INTENT_MATCHING) Log.v(
8067                            TAG, "Removing duplicate item from " + j
8068                            + " due to specific " + specificsPos);
8069                        if (ri == null) {
8070                            ri = sri;
8071                        }
8072                        j--;
8073                        N--;
8074                    }
8075                }
8076
8077                // Add this specific item to its proper place.
8078                if (ri == null) {
8079                    ri = new ResolveInfo();
8080                    ri.activityInfo = ai;
8081                }
8082                results.add(specificsPos, ri);
8083                ri.specificIndex = i;
8084                specificsPos++;
8085            }
8086        }
8087
8088        // Now we go through the remaining generic results and remove any
8089        // duplicate actions that are found here.
8090        N = results.size();
8091        for (int i=specificsPos; i<N-1; i++) {
8092            final ResolveInfo rii = results.get(i);
8093            if (rii.filter == null) {
8094                continue;
8095            }
8096
8097            // Iterate over all of the actions of this result's intent
8098            // filter...  typically this should be just one.
8099            final Iterator<String> it = rii.filter.actionsIterator();
8100            if (it == null) {
8101                continue;
8102            }
8103            while (it.hasNext()) {
8104                final String action = it.next();
8105                if (resultsAction != null && resultsAction.equals(action)) {
8106                    // If this action was explicitly requested, then don't
8107                    // remove things that have it.
8108                    continue;
8109                }
8110                for (int j=i+1; j<N; j++) {
8111                    final ResolveInfo rij = results.get(j);
8112                    if (rij.filter != null && rij.filter.hasAction(action)) {
8113                        results.remove(j);
8114                        if (DEBUG_INTENT_MATCHING) Log.v(
8115                            TAG, "Removing duplicate item from " + j
8116                            + " due to action " + action + " at " + i);
8117                        j--;
8118                        N--;
8119                    }
8120                }
8121            }
8122
8123            // If the caller didn't request filter information, drop it now
8124            // so we don't have to marshall/unmarshall it.
8125            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8126                rii.filter = null;
8127            }
8128        }
8129
8130        // Filter out the caller activity if so requested.
8131        if (caller != null) {
8132            N = results.size();
8133            for (int i=0; i<N; i++) {
8134                ActivityInfo ainfo = results.get(i).activityInfo;
8135                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8136                        && caller.getClassName().equals(ainfo.name)) {
8137                    results.remove(i);
8138                    break;
8139                }
8140            }
8141        }
8142
8143        // If the caller didn't request filter information,
8144        // drop them now so we don't have to
8145        // marshall/unmarshall it.
8146        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8147            N = results.size();
8148            for (int i=0; i<N; i++) {
8149                results.get(i).filter = null;
8150            }
8151        }
8152
8153        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8154        return results;
8155    }
8156
8157    @Override
8158    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8159            String resolvedType, int flags, int userId) {
8160        return new ParceledListSlice<>(
8161                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8162                        false /*allowDynamicSplits*/));
8163    }
8164
8165    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8166            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8167        if (!sUserManager.exists(userId)) return Collections.emptyList();
8168        final int callingUid = Binder.getCallingUid();
8169        enforceCrossUserPermission(callingUid, userId,
8170                false /*requireFullPermission*/, false /*checkShell*/,
8171                "query intent receivers");
8172        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8173        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8174                false /*includeInstantApps*/);
8175        ComponentName comp = intent.getComponent();
8176        if (comp == null) {
8177            if (intent.getSelector() != null) {
8178                intent = intent.getSelector();
8179                comp = intent.getComponent();
8180            }
8181        }
8182        if (comp != null) {
8183            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8184            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8185            if (ai != null) {
8186                // When specifying an explicit component, we prevent the activity from being
8187                // used when either 1) the calling package is normal and the activity is within
8188                // an instant application or 2) the calling package is ephemeral and the
8189                // activity is not visible to instant applications.
8190                final boolean matchInstantApp =
8191                        (flags & PackageManager.MATCH_INSTANT) != 0;
8192                final boolean matchVisibleToInstantAppOnly =
8193                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8194                final boolean matchExplicitlyVisibleOnly =
8195                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8196                final boolean isCallerInstantApp =
8197                        instantAppPkgName != null;
8198                final boolean isTargetSameInstantApp =
8199                        comp.getPackageName().equals(instantAppPkgName);
8200                final boolean isTargetInstantApp =
8201                        (ai.applicationInfo.privateFlags
8202                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8203                final boolean isTargetVisibleToInstantApp =
8204                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8205                final boolean isTargetExplicitlyVisibleToInstantApp =
8206                        isTargetVisibleToInstantApp
8207                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8208                final boolean isTargetHiddenFromInstantApp =
8209                        !isTargetVisibleToInstantApp
8210                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8211                final boolean blockResolution =
8212                        !isTargetSameInstantApp
8213                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8214                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8215                                        && isTargetHiddenFromInstantApp));
8216                if (!blockResolution) {
8217                    ResolveInfo ri = new ResolveInfo();
8218                    ri.activityInfo = ai;
8219                    list.add(ri);
8220                }
8221            }
8222            return applyPostResolutionFilter(
8223                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8224        }
8225
8226        // reader
8227        synchronized (mPackages) {
8228            String pkgName = intent.getPackage();
8229            if (pkgName == null) {
8230                final List<ResolveInfo> result =
8231                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8232                return applyPostResolutionFilter(
8233                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8234            }
8235            final PackageParser.Package pkg = mPackages.get(pkgName);
8236            if (pkg != null) {
8237                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8238                        intent, resolvedType, flags, pkg.receivers, userId);
8239                return applyPostResolutionFilter(
8240                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8241            }
8242            return Collections.emptyList();
8243        }
8244    }
8245
8246    @Override
8247    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8248        final int callingUid = Binder.getCallingUid();
8249        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8250    }
8251
8252    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8253            int userId, int callingUid) {
8254        if (!sUserManager.exists(userId)) return null;
8255        flags = updateFlagsForResolve(
8256                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8257        List<ResolveInfo> query = queryIntentServicesInternal(
8258                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8259        if (query != null) {
8260            if (query.size() >= 1) {
8261                // If there is more than one service with the same priority,
8262                // just arbitrarily pick the first one.
8263                return query.get(0);
8264            }
8265        }
8266        return null;
8267    }
8268
8269    @Override
8270    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8271            String resolvedType, int flags, int userId) {
8272        final int callingUid = Binder.getCallingUid();
8273        return new ParceledListSlice<>(queryIntentServicesInternal(
8274                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8275    }
8276
8277    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8278            String resolvedType, int flags, int userId, int callingUid,
8279            boolean includeInstantApps) {
8280        if (!sUserManager.exists(userId)) return Collections.emptyList();
8281        enforceCrossUserPermission(callingUid, userId,
8282                false /*requireFullPermission*/, false /*checkShell*/,
8283                "query intent receivers");
8284        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8285        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8286        ComponentName comp = intent.getComponent();
8287        if (comp == null) {
8288            if (intent.getSelector() != null) {
8289                intent = intent.getSelector();
8290                comp = intent.getComponent();
8291            }
8292        }
8293        if (comp != null) {
8294            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8295            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8296            if (si != null) {
8297                // When specifying an explicit component, we prevent the service from being
8298                // used when either 1) the service is in an instant application and the
8299                // caller is not the same instant application or 2) the calling package is
8300                // ephemeral and the activity is not visible to ephemeral applications.
8301                final boolean matchInstantApp =
8302                        (flags & PackageManager.MATCH_INSTANT) != 0;
8303                final boolean matchVisibleToInstantAppOnly =
8304                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8305                final boolean isCallerInstantApp =
8306                        instantAppPkgName != null;
8307                final boolean isTargetSameInstantApp =
8308                        comp.getPackageName().equals(instantAppPkgName);
8309                final boolean isTargetInstantApp =
8310                        (si.applicationInfo.privateFlags
8311                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8312                final boolean isTargetHiddenFromInstantApp =
8313                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8314                final boolean blockResolution =
8315                        !isTargetSameInstantApp
8316                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8317                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8318                                        && isTargetHiddenFromInstantApp));
8319                if (!blockResolution) {
8320                    final ResolveInfo ri = new ResolveInfo();
8321                    ri.serviceInfo = si;
8322                    list.add(ri);
8323                }
8324            }
8325            return list;
8326        }
8327
8328        // reader
8329        synchronized (mPackages) {
8330            String pkgName = intent.getPackage();
8331            if (pkgName == null) {
8332                return applyPostServiceResolutionFilter(
8333                        mServices.queryIntent(intent, resolvedType, flags, userId),
8334                        instantAppPkgName);
8335            }
8336            final PackageParser.Package pkg = mPackages.get(pkgName);
8337            if (pkg != null) {
8338                return applyPostServiceResolutionFilter(
8339                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8340                                userId),
8341                        instantAppPkgName);
8342            }
8343            return Collections.emptyList();
8344        }
8345    }
8346
8347    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8348            String instantAppPkgName) {
8349        if (instantAppPkgName == null) {
8350            return resolveInfos;
8351        }
8352        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8353            final ResolveInfo info = resolveInfos.get(i);
8354            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8355            // allow services that are defined in the provided package
8356            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8357                if (info.serviceInfo.splitName != null
8358                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8359                                info.serviceInfo.splitName)) {
8360                    // requested service is defined in a split that hasn't been installed yet.
8361                    // add the installer to the resolve list
8362                    if (DEBUG_EPHEMERAL) {
8363                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8364                    }
8365                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8366                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8367                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8368                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8369                            null /*failureIntent*/);
8370                    // make sure this resolver is the default
8371                    installerInfo.isDefault = true;
8372                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8373                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8374                    // add a non-generic filter
8375                    installerInfo.filter = new IntentFilter();
8376                    // load resources from the correct package
8377                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8378                    resolveInfos.set(i, installerInfo);
8379                }
8380                continue;
8381            }
8382            // allow services that have been explicitly exposed to ephemeral apps
8383            if (!isEphemeralApp
8384                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8385                continue;
8386            }
8387            resolveInfos.remove(i);
8388        }
8389        return resolveInfos;
8390    }
8391
8392    @Override
8393    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8394            String resolvedType, int flags, int userId) {
8395        return new ParceledListSlice<>(
8396                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8397    }
8398
8399    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8400            Intent intent, String resolvedType, int flags, int userId) {
8401        if (!sUserManager.exists(userId)) return Collections.emptyList();
8402        final int callingUid = Binder.getCallingUid();
8403        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8404        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8405                false /*includeInstantApps*/);
8406        ComponentName comp = intent.getComponent();
8407        if (comp == null) {
8408            if (intent.getSelector() != null) {
8409                intent = intent.getSelector();
8410                comp = intent.getComponent();
8411            }
8412        }
8413        if (comp != null) {
8414            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8415            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8416            if (pi != null) {
8417                // When specifying an explicit component, we prevent the provider from being
8418                // used when either 1) the provider is in an instant application and the
8419                // caller is not the same instant application or 2) the calling package is an
8420                // instant application and the provider is not visible to instant applications.
8421                final boolean matchInstantApp =
8422                        (flags & PackageManager.MATCH_INSTANT) != 0;
8423                final boolean matchVisibleToInstantAppOnly =
8424                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8425                final boolean isCallerInstantApp =
8426                        instantAppPkgName != null;
8427                final boolean isTargetSameInstantApp =
8428                        comp.getPackageName().equals(instantAppPkgName);
8429                final boolean isTargetInstantApp =
8430                        (pi.applicationInfo.privateFlags
8431                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8432                final boolean isTargetHiddenFromInstantApp =
8433                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8434                final boolean blockResolution =
8435                        !isTargetSameInstantApp
8436                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8437                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8438                                        && isTargetHiddenFromInstantApp));
8439                if (!blockResolution) {
8440                    final ResolveInfo ri = new ResolveInfo();
8441                    ri.providerInfo = pi;
8442                    list.add(ri);
8443                }
8444            }
8445            return list;
8446        }
8447
8448        // reader
8449        synchronized (mPackages) {
8450            String pkgName = intent.getPackage();
8451            if (pkgName == null) {
8452                return applyPostContentProviderResolutionFilter(
8453                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8454                        instantAppPkgName);
8455            }
8456            final PackageParser.Package pkg = mPackages.get(pkgName);
8457            if (pkg != null) {
8458                return applyPostContentProviderResolutionFilter(
8459                        mProviders.queryIntentForPackage(
8460                        intent, resolvedType, flags, pkg.providers, userId),
8461                        instantAppPkgName);
8462            }
8463            return Collections.emptyList();
8464        }
8465    }
8466
8467    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8468            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8469        if (instantAppPkgName == null) {
8470            return resolveInfos;
8471        }
8472        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8473            final ResolveInfo info = resolveInfos.get(i);
8474            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8475            // allow providers that are defined in the provided package
8476            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8477                if (info.providerInfo.splitName != null
8478                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8479                                info.providerInfo.splitName)) {
8480                    // requested provider is defined in a split that hasn't been installed yet.
8481                    // add the installer to the resolve list
8482                    if (DEBUG_EPHEMERAL) {
8483                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8484                    }
8485                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8486                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8487                            info.providerInfo.packageName, info.providerInfo.splitName,
8488                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8489                            null /*failureIntent*/);
8490                    // make sure this resolver is the default
8491                    installerInfo.isDefault = true;
8492                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8493                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8494                    // add a non-generic filter
8495                    installerInfo.filter = new IntentFilter();
8496                    // load resources from the correct package
8497                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8498                    resolveInfos.set(i, installerInfo);
8499                }
8500                continue;
8501            }
8502            // allow providers that have been explicitly exposed to instant applications
8503            if (!isEphemeralApp
8504                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8505                continue;
8506            }
8507            resolveInfos.remove(i);
8508        }
8509        return resolveInfos;
8510    }
8511
8512    @Override
8513    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8514        final int callingUid = Binder.getCallingUid();
8515        if (getInstantAppPackageName(callingUid) != null) {
8516            return ParceledListSlice.emptyList();
8517        }
8518        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8519        flags = updateFlagsForPackage(flags, userId, null);
8520        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8521        enforceCrossUserPermission(callingUid, userId,
8522                true /* requireFullPermission */, false /* checkShell */,
8523                "get installed packages");
8524
8525        // writer
8526        synchronized (mPackages) {
8527            ArrayList<PackageInfo> list;
8528            if (listUninstalled) {
8529                list = new ArrayList<>(mSettings.mPackages.size());
8530                for (PackageSetting ps : mSettings.mPackages.values()) {
8531                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8532                        continue;
8533                    }
8534                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8535                        continue;
8536                    }
8537                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8538                    if (pi != null) {
8539                        list.add(pi);
8540                    }
8541                }
8542            } else {
8543                list = new ArrayList<>(mPackages.size());
8544                for (PackageParser.Package p : mPackages.values()) {
8545                    final PackageSetting ps = (PackageSetting) p.mExtras;
8546                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8547                        continue;
8548                    }
8549                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8550                        continue;
8551                    }
8552                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8553                            p.mExtras, flags, userId);
8554                    if (pi != null) {
8555                        list.add(pi);
8556                    }
8557                }
8558            }
8559
8560            return new ParceledListSlice<>(list);
8561        }
8562    }
8563
8564    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8565            String[] permissions, boolean[] tmp, int flags, int userId) {
8566        int numMatch = 0;
8567        final PermissionsState permissionsState = ps.getPermissionsState();
8568        for (int i=0; i<permissions.length; i++) {
8569            final String permission = permissions[i];
8570            if (permissionsState.hasPermission(permission, userId)) {
8571                tmp[i] = true;
8572                numMatch++;
8573            } else {
8574                tmp[i] = false;
8575            }
8576        }
8577        if (numMatch == 0) {
8578            return;
8579        }
8580        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8581
8582        // The above might return null in cases of uninstalled apps or install-state
8583        // skew across users/profiles.
8584        if (pi != null) {
8585            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8586                if (numMatch == permissions.length) {
8587                    pi.requestedPermissions = permissions;
8588                } else {
8589                    pi.requestedPermissions = new String[numMatch];
8590                    numMatch = 0;
8591                    for (int i=0; i<permissions.length; i++) {
8592                        if (tmp[i]) {
8593                            pi.requestedPermissions[numMatch] = permissions[i];
8594                            numMatch++;
8595                        }
8596                    }
8597                }
8598            }
8599            list.add(pi);
8600        }
8601    }
8602
8603    @Override
8604    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8605            String[] permissions, int flags, int userId) {
8606        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8607        flags = updateFlagsForPackage(flags, userId, permissions);
8608        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8609                true /* requireFullPermission */, false /* checkShell */,
8610                "get packages holding permissions");
8611        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8612
8613        // writer
8614        synchronized (mPackages) {
8615            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8616            boolean[] tmpBools = new boolean[permissions.length];
8617            if (listUninstalled) {
8618                for (PackageSetting ps : mSettings.mPackages.values()) {
8619                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8620                            userId);
8621                }
8622            } else {
8623                for (PackageParser.Package pkg : mPackages.values()) {
8624                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8625                    if (ps != null) {
8626                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8627                                userId);
8628                    }
8629                }
8630            }
8631
8632            return new ParceledListSlice<PackageInfo>(list);
8633        }
8634    }
8635
8636    @Override
8637    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8638        final int callingUid = Binder.getCallingUid();
8639        if (getInstantAppPackageName(callingUid) != null) {
8640            return ParceledListSlice.emptyList();
8641        }
8642        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8643        flags = updateFlagsForApplication(flags, userId, null);
8644        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8645
8646        // writer
8647        synchronized (mPackages) {
8648            ArrayList<ApplicationInfo> list;
8649            if (listUninstalled) {
8650                list = new ArrayList<>(mSettings.mPackages.size());
8651                for (PackageSetting ps : mSettings.mPackages.values()) {
8652                    ApplicationInfo ai;
8653                    int effectiveFlags = flags;
8654                    if (ps.isSystem()) {
8655                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8656                    }
8657                    if (ps.pkg != null) {
8658                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8659                            continue;
8660                        }
8661                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8662                            continue;
8663                        }
8664                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8665                                ps.readUserState(userId), userId);
8666                        if (ai != null) {
8667                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8668                        }
8669                    } else {
8670                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8671                        // and already converts to externally visible package name
8672                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8673                                callingUid, effectiveFlags, userId);
8674                    }
8675                    if (ai != null) {
8676                        list.add(ai);
8677                    }
8678                }
8679            } else {
8680                list = new ArrayList<>(mPackages.size());
8681                for (PackageParser.Package p : mPackages.values()) {
8682                    if (p.mExtras != null) {
8683                        PackageSetting ps = (PackageSetting) p.mExtras;
8684                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8685                            continue;
8686                        }
8687                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8688                            continue;
8689                        }
8690                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8691                                ps.readUserState(userId), userId);
8692                        if (ai != null) {
8693                            ai.packageName = resolveExternalPackageNameLPr(p);
8694                            list.add(ai);
8695                        }
8696                    }
8697                }
8698            }
8699
8700            return new ParceledListSlice<>(list);
8701        }
8702    }
8703
8704    @Override
8705    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8706        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8707            return null;
8708        }
8709        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8710            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8711                    "getEphemeralApplications");
8712        }
8713        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8714                true /* requireFullPermission */, false /* checkShell */,
8715                "getEphemeralApplications");
8716        synchronized (mPackages) {
8717            List<InstantAppInfo> instantApps = mInstantAppRegistry
8718                    .getInstantAppsLPr(userId);
8719            if (instantApps != null) {
8720                return new ParceledListSlice<>(instantApps);
8721            }
8722        }
8723        return null;
8724    }
8725
8726    @Override
8727    public boolean isInstantApp(String packageName, int userId) {
8728        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8729                true /* requireFullPermission */, false /* checkShell */,
8730                "isInstantApp");
8731        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8732            return false;
8733        }
8734
8735        synchronized (mPackages) {
8736            int callingUid = Binder.getCallingUid();
8737            if (Process.isIsolated(callingUid)) {
8738                callingUid = mIsolatedOwners.get(callingUid);
8739            }
8740            final PackageSetting ps = mSettings.mPackages.get(packageName);
8741            PackageParser.Package pkg = mPackages.get(packageName);
8742            final boolean returnAllowed =
8743                    ps != null
8744                    && (isCallerSameApp(packageName, callingUid)
8745                            || canViewInstantApps(callingUid, userId)
8746                            || mInstantAppRegistry.isInstantAccessGranted(
8747                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8748            if (returnAllowed) {
8749                return ps.getInstantApp(userId);
8750            }
8751        }
8752        return false;
8753    }
8754
8755    @Override
8756    public byte[] getInstantAppCookie(String packageName, int userId) {
8757        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8758            return null;
8759        }
8760
8761        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8762                true /* requireFullPermission */, false /* checkShell */,
8763                "getInstantAppCookie");
8764        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8765            return null;
8766        }
8767        synchronized (mPackages) {
8768            return mInstantAppRegistry.getInstantAppCookieLPw(
8769                    packageName, userId);
8770        }
8771    }
8772
8773    @Override
8774    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8775        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8776            return true;
8777        }
8778
8779        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8780                true /* requireFullPermission */, true /* checkShell */,
8781                "setInstantAppCookie");
8782        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8783            return false;
8784        }
8785        synchronized (mPackages) {
8786            return mInstantAppRegistry.setInstantAppCookieLPw(
8787                    packageName, cookie, userId);
8788        }
8789    }
8790
8791    @Override
8792    public Bitmap getInstantAppIcon(String packageName, int userId) {
8793        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8794            return null;
8795        }
8796
8797        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8798            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8799                    "getInstantAppIcon");
8800        }
8801        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8802                true /* requireFullPermission */, false /* checkShell */,
8803                "getInstantAppIcon");
8804
8805        synchronized (mPackages) {
8806            return mInstantAppRegistry.getInstantAppIconLPw(
8807                    packageName, userId);
8808        }
8809    }
8810
8811    private boolean isCallerSameApp(String packageName, int uid) {
8812        PackageParser.Package pkg = mPackages.get(packageName);
8813        return pkg != null
8814                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8815    }
8816
8817    @Override
8818    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8819        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8820            return ParceledListSlice.emptyList();
8821        }
8822        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8823    }
8824
8825    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8826        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8827
8828        // reader
8829        synchronized (mPackages) {
8830            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8831            final int userId = UserHandle.getCallingUserId();
8832            while (i.hasNext()) {
8833                final PackageParser.Package p = i.next();
8834                if (p.applicationInfo == null) continue;
8835
8836                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8837                        && !p.applicationInfo.isDirectBootAware();
8838                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8839                        && p.applicationInfo.isDirectBootAware();
8840
8841                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8842                        && (!mSafeMode || isSystemApp(p))
8843                        && (matchesUnaware || matchesAware)) {
8844                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8845                    if (ps != null) {
8846                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8847                                ps.readUserState(userId), userId);
8848                        if (ai != null) {
8849                            finalList.add(ai);
8850                        }
8851                    }
8852                }
8853            }
8854        }
8855
8856        return finalList;
8857    }
8858
8859    @Override
8860    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8861        if (!sUserManager.exists(userId)) return null;
8862        flags = updateFlagsForComponent(flags, userId, name);
8863        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8864        // reader
8865        synchronized (mPackages) {
8866            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8867            PackageSetting ps = provider != null
8868                    ? mSettings.mPackages.get(provider.owner.packageName)
8869                    : null;
8870            if (ps != null) {
8871                final boolean isInstantApp = ps.getInstantApp(userId);
8872                // normal application; filter out instant application provider
8873                if (instantAppPkgName == null && isInstantApp) {
8874                    return null;
8875                }
8876                // instant application; filter out other instant applications
8877                if (instantAppPkgName != null
8878                        && isInstantApp
8879                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8880                    return null;
8881                }
8882                // instant application; filter out non-exposed provider
8883                if (instantAppPkgName != null
8884                        && !isInstantApp
8885                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8886                    return null;
8887                }
8888                // provider not enabled
8889                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8890                    return null;
8891                }
8892                return PackageParser.generateProviderInfo(
8893                        provider, flags, ps.readUserState(userId), userId);
8894            }
8895            return null;
8896        }
8897    }
8898
8899    /**
8900     * @deprecated
8901     */
8902    @Deprecated
8903    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8904        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8905            return;
8906        }
8907        // reader
8908        synchronized (mPackages) {
8909            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8910                    .entrySet().iterator();
8911            final int userId = UserHandle.getCallingUserId();
8912            while (i.hasNext()) {
8913                Map.Entry<String, PackageParser.Provider> entry = i.next();
8914                PackageParser.Provider p = entry.getValue();
8915                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8916
8917                if (ps != null && p.syncable
8918                        && (!mSafeMode || (p.info.applicationInfo.flags
8919                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8920                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8921                            ps.readUserState(userId), userId);
8922                    if (info != null) {
8923                        outNames.add(entry.getKey());
8924                        outInfo.add(info);
8925                    }
8926                }
8927            }
8928        }
8929    }
8930
8931    @Override
8932    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8933            int uid, int flags, String metaDataKey) {
8934        final int callingUid = Binder.getCallingUid();
8935        final int userId = processName != null ? UserHandle.getUserId(uid)
8936                : UserHandle.getCallingUserId();
8937        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8938        flags = updateFlagsForComponent(flags, userId, processName);
8939        ArrayList<ProviderInfo> finalList = null;
8940        // reader
8941        synchronized (mPackages) {
8942            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8943            while (i.hasNext()) {
8944                final PackageParser.Provider p = i.next();
8945                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8946                if (ps != null && p.info.authority != null
8947                        && (processName == null
8948                                || (p.info.processName.equals(processName)
8949                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8950                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8951
8952                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8953                    // parameter.
8954                    if (metaDataKey != null
8955                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8956                        continue;
8957                    }
8958                    final ComponentName component =
8959                            new ComponentName(p.info.packageName, p.info.name);
8960                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8961                        continue;
8962                    }
8963                    if (finalList == null) {
8964                        finalList = new ArrayList<ProviderInfo>(3);
8965                    }
8966                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8967                            ps.readUserState(userId), userId);
8968                    if (info != null) {
8969                        finalList.add(info);
8970                    }
8971                }
8972            }
8973        }
8974
8975        if (finalList != null) {
8976            Collections.sort(finalList, mProviderInitOrderSorter);
8977            return new ParceledListSlice<ProviderInfo>(finalList);
8978        }
8979
8980        return ParceledListSlice.emptyList();
8981    }
8982
8983    @Override
8984    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8985        // reader
8986        synchronized (mPackages) {
8987            final int callingUid = Binder.getCallingUid();
8988            final int callingUserId = UserHandle.getUserId(callingUid);
8989            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8990            if (ps == null) return null;
8991            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8992                return null;
8993            }
8994            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8995            return PackageParser.generateInstrumentationInfo(i, flags);
8996        }
8997    }
8998
8999    @Override
9000    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
9001            String targetPackage, int flags) {
9002        final int callingUid = Binder.getCallingUid();
9003        final int callingUserId = UserHandle.getUserId(callingUid);
9004        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
9005        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
9006            return ParceledListSlice.emptyList();
9007        }
9008        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
9009    }
9010
9011    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
9012            int flags) {
9013        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
9014
9015        // reader
9016        synchronized (mPackages) {
9017            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
9018            while (i.hasNext()) {
9019                final PackageParser.Instrumentation p = i.next();
9020                if (targetPackage == null
9021                        || targetPackage.equals(p.info.targetPackage)) {
9022                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
9023                            flags);
9024                    if (ii != null) {
9025                        finalList.add(ii);
9026                    }
9027                }
9028            }
9029        }
9030
9031        return finalList;
9032    }
9033
9034    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9035        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9036        try {
9037            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9038        } finally {
9039            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9040        }
9041    }
9042
9043    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9044        final File[] files = dir.listFiles();
9045        if (ArrayUtils.isEmpty(files)) {
9046            Log.d(TAG, "No files in app dir " + dir);
9047            return;
9048        }
9049
9050        if (DEBUG_PACKAGE_SCANNING) {
9051            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9052                    + " flags=0x" + Integer.toHexString(parseFlags));
9053        }
9054        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9055                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9056                mParallelPackageParserCallback);
9057
9058        // Submit files for parsing in parallel
9059        int fileCount = 0;
9060        for (File file : files) {
9061            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9062                    && !PackageInstallerService.isStageName(file.getName());
9063            if (!isPackage) {
9064                // Ignore entries which are not packages
9065                continue;
9066            }
9067            parallelPackageParser.submit(file, parseFlags);
9068            fileCount++;
9069        }
9070
9071        // Process results one by one
9072        for (; fileCount > 0; fileCount--) {
9073            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9074            Throwable throwable = parseResult.throwable;
9075            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9076
9077            if (throwable == null) {
9078                // Static shared libraries have synthetic package names
9079                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9080                    renameStaticSharedLibraryPackage(parseResult.pkg);
9081                }
9082                try {
9083                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9084                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9085                                currentTime, null);
9086                    }
9087                } catch (PackageManagerException e) {
9088                    errorCode = e.error;
9089                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9090                }
9091            } else if (throwable instanceof PackageParser.PackageParserException) {
9092                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9093                        throwable;
9094                errorCode = e.error;
9095                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9096            } else {
9097                throw new IllegalStateException("Unexpected exception occurred while parsing "
9098                        + parseResult.scanFile, throwable);
9099            }
9100
9101            // Delete invalid userdata apps
9102            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9103                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9104                logCriticalInfo(Log.WARN,
9105                        "Deleting invalid package at " + parseResult.scanFile);
9106                removeCodePathLI(parseResult.scanFile);
9107            }
9108        }
9109        parallelPackageParser.close();
9110    }
9111
9112    private static File getSettingsProblemFile() {
9113        File dataDir = Environment.getDataDirectory();
9114        File systemDir = new File(dataDir, "system");
9115        File fname = new File(systemDir, "uiderrors.txt");
9116        return fname;
9117    }
9118
9119    static void reportSettingsProblem(int priority, String msg) {
9120        logCriticalInfo(priority, msg);
9121    }
9122
9123    public static void logCriticalInfo(int priority, String msg) {
9124        Slog.println(priority, TAG, msg);
9125        EventLogTags.writePmCriticalInfo(msg);
9126        try {
9127            File fname = getSettingsProblemFile();
9128            FileOutputStream out = new FileOutputStream(fname, true);
9129            PrintWriter pw = new FastPrintWriter(out);
9130            SimpleDateFormat formatter = new SimpleDateFormat();
9131            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9132            pw.println(dateString + ": " + msg);
9133            pw.close();
9134            FileUtils.setPermissions(
9135                    fname.toString(),
9136                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9137                    -1, -1);
9138        } catch (java.io.IOException e) {
9139        }
9140    }
9141
9142    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9143        if (srcFile.isDirectory()) {
9144            final File baseFile = new File(pkg.baseCodePath);
9145            long maxModifiedTime = baseFile.lastModified();
9146            if (pkg.splitCodePaths != null) {
9147                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9148                    final File splitFile = new File(pkg.splitCodePaths[i]);
9149                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9150                }
9151            }
9152            return maxModifiedTime;
9153        }
9154        return srcFile.lastModified();
9155    }
9156
9157    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9158            final int policyFlags) throws PackageManagerException {
9159        // When upgrading from pre-N MR1, verify the package time stamp using the package
9160        // directory and not the APK file.
9161        final long lastModifiedTime = mIsPreNMR1Upgrade
9162                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9163        if (ps != null
9164                && ps.codePath.equals(srcFile)
9165                && ps.timeStamp == lastModifiedTime
9166                && !isCompatSignatureUpdateNeeded(pkg)
9167                && !isRecoverSignatureUpdateNeeded(pkg)) {
9168            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9169            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9170            ArraySet<PublicKey> signingKs;
9171            synchronized (mPackages) {
9172                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9173            }
9174            if (ps.signatures.mSignatures != null
9175                    && ps.signatures.mSignatures.length != 0
9176                    && signingKs != null) {
9177                // Optimization: reuse the existing cached certificates
9178                // if the package appears to be unchanged.
9179                pkg.mSignatures = ps.signatures.mSignatures;
9180                pkg.mSigningKeys = signingKs;
9181                return;
9182            }
9183
9184            Slog.w(TAG, "PackageSetting for " + ps.name
9185                    + " is missing signatures.  Collecting certs again to recover them.");
9186        } else {
9187            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9188        }
9189
9190        try {
9191            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9192            PackageParser.collectCertificates(pkg, policyFlags);
9193        } catch (PackageParserException e) {
9194            throw PackageManagerException.from(e);
9195        } finally {
9196            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9197        }
9198    }
9199
9200    /**
9201     *  Traces a package scan.
9202     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9203     */
9204    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9205            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9206        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9207        try {
9208            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9209        } finally {
9210            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9211        }
9212    }
9213
9214    /**
9215     *  Scans a package and returns the newly parsed package.
9216     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9217     */
9218    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9219            long currentTime, UserHandle user) throws PackageManagerException {
9220        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9221        PackageParser pp = new PackageParser();
9222        pp.setSeparateProcesses(mSeparateProcesses);
9223        pp.setOnlyCoreApps(mOnlyCore);
9224        pp.setDisplayMetrics(mMetrics);
9225        pp.setCallback(mPackageParserCallback);
9226
9227        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9228            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9229        }
9230
9231        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9232        final PackageParser.Package pkg;
9233        try {
9234            pkg = pp.parsePackage(scanFile, parseFlags);
9235        } catch (PackageParserException e) {
9236            throw PackageManagerException.from(e);
9237        } finally {
9238            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9239        }
9240
9241        // Static shared libraries have synthetic package names
9242        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9243            renameStaticSharedLibraryPackage(pkg);
9244        }
9245
9246        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9247    }
9248
9249    /**
9250     *  Scans a package and returns the newly parsed package.
9251     *  @throws PackageManagerException on a parse error.
9252     */
9253    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9254            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9255            throws PackageManagerException {
9256        // If the package has children and this is the first dive in the function
9257        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9258        // packages (parent and children) would be successfully scanned before the
9259        // actual scan since scanning mutates internal state and we want to atomically
9260        // install the package and its children.
9261        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9262            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9263                scanFlags |= SCAN_CHECK_ONLY;
9264            }
9265        } else {
9266            scanFlags &= ~SCAN_CHECK_ONLY;
9267        }
9268
9269        // Scan the parent
9270        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9271                scanFlags, currentTime, user);
9272
9273        // Scan the children
9274        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9275        for (int i = 0; i < childCount; i++) {
9276            PackageParser.Package childPackage = pkg.childPackages.get(i);
9277            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9278                    currentTime, user);
9279        }
9280
9281
9282        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9283            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9284        }
9285
9286        return scannedPkg;
9287    }
9288
9289    /**
9290     *  Scans a package and returns the newly parsed package.
9291     *  @throws PackageManagerException on a parse error.
9292     */
9293    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9294            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9295            throws PackageManagerException {
9296        PackageSetting ps = null;
9297        PackageSetting updatedPkg;
9298        // reader
9299        synchronized (mPackages) {
9300            // Look to see if we already know about this package.
9301            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9302            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9303                // This package has been renamed to its original name.  Let's
9304                // use that.
9305                ps = mSettings.getPackageLPr(oldName);
9306            }
9307            // If there was no original package, see one for the real package name.
9308            if (ps == null) {
9309                ps = mSettings.getPackageLPr(pkg.packageName);
9310            }
9311            // Check to see if this package could be hiding/updating a system
9312            // package.  Must look for it either under the original or real
9313            // package name depending on our state.
9314            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9315            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9316
9317            // If this is a package we don't know about on the system partition, we
9318            // may need to remove disabled child packages on the system partition
9319            // or may need to not add child packages if the parent apk is updated
9320            // on the data partition and no longer defines this child package.
9321            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9322                // If this is a parent package for an updated system app and this system
9323                // app got an OTA update which no longer defines some of the child packages
9324                // we have to prune them from the disabled system packages.
9325                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9326                if (disabledPs != null) {
9327                    final int scannedChildCount = (pkg.childPackages != null)
9328                            ? pkg.childPackages.size() : 0;
9329                    final int disabledChildCount = disabledPs.childPackageNames != null
9330                            ? disabledPs.childPackageNames.size() : 0;
9331                    for (int i = 0; i < disabledChildCount; i++) {
9332                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9333                        boolean disabledPackageAvailable = false;
9334                        for (int j = 0; j < scannedChildCount; j++) {
9335                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9336                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9337                                disabledPackageAvailable = true;
9338                                break;
9339                            }
9340                         }
9341                         if (!disabledPackageAvailable) {
9342                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9343                         }
9344                    }
9345                }
9346            }
9347        }
9348
9349        final boolean isUpdatedPkg = updatedPkg != null;
9350        final boolean isUpdatedSystemPkg = isUpdatedPkg
9351                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9352        boolean isUpdatedPkgBetter = false;
9353        // First check if this is a system package that may involve an update
9354        if (isUpdatedSystemPkg) {
9355            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9356            // it needs to drop FLAG_PRIVILEGED.
9357            if (locationIsPrivileged(scanFile)) {
9358                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9359            } else {
9360                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9361            }
9362
9363            if (ps != null && !ps.codePath.equals(scanFile)) {
9364                // The path has changed from what was last scanned...  check the
9365                // version of the new path against what we have stored to determine
9366                // what to do.
9367                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9368                if (pkg.mVersionCode <= ps.versionCode) {
9369                    // The system package has been updated and the code path does not match
9370                    // Ignore entry. Skip it.
9371                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9372                            + " ignored: updated version " + ps.versionCode
9373                            + " better than this " + pkg.mVersionCode);
9374                    if (!updatedPkg.codePath.equals(scanFile)) {
9375                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9376                                + ps.name + " changing from " + updatedPkg.codePathString
9377                                + " to " + scanFile);
9378                        updatedPkg.codePath = scanFile;
9379                        updatedPkg.codePathString = scanFile.toString();
9380                        updatedPkg.resourcePath = scanFile;
9381                        updatedPkg.resourcePathString = scanFile.toString();
9382                    }
9383                    updatedPkg.pkg = pkg;
9384                    updatedPkg.versionCode = pkg.mVersionCode;
9385
9386                    // Update the disabled system child packages to point to the package too.
9387                    final int childCount = updatedPkg.childPackageNames != null
9388                            ? updatedPkg.childPackageNames.size() : 0;
9389                    for (int i = 0; i < childCount; i++) {
9390                        String childPackageName = updatedPkg.childPackageNames.get(i);
9391                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9392                                childPackageName);
9393                        if (updatedChildPkg != null) {
9394                            updatedChildPkg.pkg = pkg;
9395                            updatedChildPkg.versionCode = pkg.mVersionCode;
9396                        }
9397                    }
9398                } else {
9399                    // The current app on the system partition is better than
9400                    // what we have updated to on the data partition; switch
9401                    // back to the system partition version.
9402                    // At this point, its safely assumed that package installation for
9403                    // apps in system partition will go through. If not there won't be a working
9404                    // version of the app
9405                    // writer
9406                    synchronized (mPackages) {
9407                        // Just remove the loaded entries from package lists.
9408                        mPackages.remove(ps.name);
9409                    }
9410
9411                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9412                            + " reverting from " + ps.codePathString
9413                            + ": new version " + pkg.mVersionCode
9414                            + " better than installed " + ps.versionCode);
9415
9416                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9417                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9418                    synchronized (mInstallLock) {
9419                        args.cleanUpResourcesLI();
9420                    }
9421                    synchronized (mPackages) {
9422                        mSettings.enableSystemPackageLPw(ps.name);
9423                    }
9424                    isUpdatedPkgBetter = true;
9425                }
9426            }
9427        }
9428
9429        String resourcePath = null;
9430        String baseResourcePath = null;
9431        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9432            if (ps != null && ps.resourcePathString != null) {
9433                resourcePath = ps.resourcePathString;
9434                baseResourcePath = ps.resourcePathString;
9435            } else {
9436                // Should not happen at all. Just log an error.
9437                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9438            }
9439        } else {
9440            resourcePath = pkg.codePath;
9441            baseResourcePath = pkg.baseCodePath;
9442        }
9443
9444        // Set application objects path explicitly.
9445        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9446        pkg.setApplicationInfoCodePath(pkg.codePath);
9447        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9448        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9449        pkg.setApplicationInfoResourcePath(resourcePath);
9450        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9451        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9452
9453        // throw an exception if we have an update to a system application, but, it's not more
9454        // recent than the package we've already scanned
9455        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9456            // Set CPU Abis to application info.
9457            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9458                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9459                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9460            } else {
9461                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9462                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9463            }
9464
9465            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9466                    + scanFile + " ignored: updated version " + ps.versionCode
9467                    + " better than this " + pkg.mVersionCode);
9468        }
9469
9470        if (isUpdatedPkg) {
9471            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9472            // initially
9473            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9474
9475            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9476            // flag set initially
9477            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9478                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9479            }
9480        }
9481
9482        // Verify certificates against what was last scanned
9483        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9484
9485        /*
9486         * A new system app appeared, but we already had a non-system one of the
9487         * same name installed earlier.
9488         */
9489        boolean shouldHideSystemApp = false;
9490        if (!isUpdatedPkg && ps != null
9491                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9492            /*
9493             * Check to make sure the signatures match first. If they don't,
9494             * wipe the installed application and its data.
9495             */
9496            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9497                    != PackageManager.SIGNATURE_MATCH) {
9498                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9499                        + " signatures don't match existing userdata copy; removing");
9500                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9501                        "scanPackageInternalLI")) {
9502                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9503                }
9504                ps = null;
9505            } else {
9506                /*
9507                 * If the newly-added system app is an older version than the
9508                 * already installed version, hide it. It will be scanned later
9509                 * and re-added like an update.
9510                 */
9511                if (pkg.mVersionCode <= ps.versionCode) {
9512                    shouldHideSystemApp = true;
9513                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9514                            + " but new version " + pkg.mVersionCode + " better than installed "
9515                            + ps.versionCode + "; hiding system");
9516                } else {
9517                    /*
9518                     * The newly found system app is a newer version that the
9519                     * one previously installed. Simply remove the
9520                     * already-installed application and replace it with our own
9521                     * while keeping the application data.
9522                     */
9523                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9524                            + " reverting from " + ps.codePathString + ": new version "
9525                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9526                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9527                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9528                    synchronized (mInstallLock) {
9529                        args.cleanUpResourcesLI();
9530                    }
9531                }
9532            }
9533        }
9534
9535        // The apk is forward locked (not public) if its code and resources
9536        // are kept in different files. (except for app in either system or
9537        // vendor path).
9538        // TODO grab this value from PackageSettings
9539        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9540            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9541                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9542            }
9543        }
9544
9545        final int userId = ((user == null) ? 0 : user.getIdentifier());
9546        if (ps != null && ps.getInstantApp(userId)) {
9547            scanFlags |= SCAN_AS_INSTANT_APP;
9548        }
9549        if (ps != null && ps.getVirtulalPreload(userId)) {
9550            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9551        }
9552
9553        // Note that we invoke the following method only if we are about to unpack an application
9554        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9555                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9556
9557        /*
9558         * If the system app should be overridden by a previously installed
9559         * data, hide the system app now and let the /data/app scan pick it up
9560         * again.
9561         */
9562        if (shouldHideSystemApp) {
9563            synchronized (mPackages) {
9564                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9565            }
9566        }
9567
9568        return scannedPkg;
9569    }
9570
9571    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9572        // Derive the new package synthetic package name
9573        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9574                + pkg.staticSharedLibVersion);
9575    }
9576
9577    private static String fixProcessName(String defProcessName,
9578            String processName) {
9579        if (processName == null) {
9580            return defProcessName;
9581        }
9582        return processName;
9583    }
9584
9585    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9586            throws PackageManagerException {
9587        if (pkgSetting.signatures.mSignatures != null) {
9588            // Already existing package. Make sure signatures match
9589            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9590                    == PackageManager.SIGNATURE_MATCH;
9591            if (!match) {
9592                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9593                        == PackageManager.SIGNATURE_MATCH;
9594            }
9595            if (!match) {
9596                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9597                        == PackageManager.SIGNATURE_MATCH;
9598            }
9599            if (!match) {
9600                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9601                        + pkg.packageName + " signatures do not match the "
9602                        + "previously installed version; ignoring!");
9603            }
9604        }
9605
9606        // Check for shared user signatures
9607        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9608            // Already existing package. Make sure signatures match
9609            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9610                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9611            if (!match) {
9612                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9613                        == PackageManager.SIGNATURE_MATCH;
9614            }
9615            if (!match) {
9616                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9617                        == PackageManager.SIGNATURE_MATCH;
9618            }
9619            if (!match) {
9620                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9621                        "Package " + pkg.packageName
9622                        + " has no signatures that match those in shared user "
9623                        + pkgSetting.sharedUser.name + "; ignoring!");
9624            }
9625        }
9626    }
9627
9628    /**
9629     * Enforces that only the system UID or root's UID can call a method exposed
9630     * via Binder.
9631     *
9632     * @param message used as message if SecurityException is thrown
9633     * @throws SecurityException if the caller is not system or root
9634     */
9635    private static final void enforceSystemOrRoot(String message) {
9636        final int uid = Binder.getCallingUid();
9637        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9638            throw new SecurityException(message);
9639        }
9640    }
9641
9642    @Override
9643    public void performFstrimIfNeeded() {
9644        enforceSystemOrRoot("Only the system can request fstrim");
9645
9646        // Before everything else, see whether we need to fstrim.
9647        try {
9648            IStorageManager sm = PackageHelper.getStorageManager();
9649            if (sm != null) {
9650                boolean doTrim = false;
9651                final long interval = android.provider.Settings.Global.getLong(
9652                        mContext.getContentResolver(),
9653                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9654                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9655                if (interval > 0) {
9656                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9657                    if (timeSinceLast > interval) {
9658                        doTrim = true;
9659                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9660                                + "; running immediately");
9661                    }
9662                }
9663                if (doTrim) {
9664                    final boolean dexOptDialogShown;
9665                    synchronized (mPackages) {
9666                        dexOptDialogShown = mDexOptDialogShown;
9667                    }
9668                    if (!isFirstBoot() && dexOptDialogShown) {
9669                        try {
9670                            ActivityManager.getService().showBootMessage(
9671                                    mContext.getResources().getString(
9672                                            R.string.android_upgrading_fstrim), true);
9673                        } catch (RemoteException e) {
9674                        }
9675                    }
9676                    sm.runMaintenance();
9677                }
9678            } else {
9679                Slog.e(TAG, "storageManager service unavailable!");
9680            }
9681        } catch (RemoteException e) {
9682            // Can't happen; StorageManagerService is local
9683        }
9684    }
9685
9686    @Override
9687    public void updatePackagesIfNeeded() {
9688        enforceSystemOrRoot("Only the system can request package update");
9689
9690        // We need to re-extract after an OTA.
9691        boolean causeUpgrade = isUpgrade();
9692
9693        // First boot or factory reset.
9694        // Note: we also handle devices that are upgrading to N right now as if it is their
9695        //       first boot, as they do not have profile data.
9696        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9697
9698        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9699        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9700
9701        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9702            return;
9703        }
9704
9705        List<PackageParser.Package> pkgs;
9706        synchronized (mPackages) {
9707            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9708        }
9709
9710        final long startTime = System.nanoTime();
9711        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9712                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9713                    false /* bootComplete */);
9714
9715        final int elapsedTimeSeconds =
9716                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9717
9718        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9719        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9720        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9721        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9722        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9723    }
9724
9725    /*
9726     * Return the prebuilt profile path given a package base code path.
9727     */
9728    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9729        return pkg.baseCodePath + ".prof";
9730    }
9731
9732    /**
9733     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9734     * containing statistics about the invocation. The array consists of three elements,
9735     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9736     * and {@code numberOfPackagesFailed}.
9737     */
9738    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9739            final String compilerFilter, boolean bootComplete) {
9740
9741        int numberOfPackagesVisited = 0;
9742        int numberOfPackagesOptimized = 0;
9743        int numberOfPackagesSkipped = 0;
9744        int numberOfPackagesFailed = 0;
9745        final int numberOfPackagesToDexopt = pkgs.size();
9746
9747        for (PackageParser.Package pkg : pkgs) {
9748            numberOfPackagesVisited++;
9749
9750            boolean useProfileForDexopt = false;
9751
9752            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9753                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9754                // that are already compiled.
9755                File profileFile = new File(getPrebuildProfilePath(pkg));
9756                // Copy profile if it exists.
9757                if (profileFile.exists()) {
9758                    try {
9759                        // We could also do this lazily before calling dexopt in
9760                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9761                        // is that we don't have a good way to say "do this only once".
9762                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9763                                pkg.applicationInfo.uid, pkg.packageName)) {
9764                            Log.e(TAG, "Installer failed to copy system profile!");
9765                        } else {
9766                            // Disabled as this causes speed-profile compilation during first boot
9767                            // even if things are already compiled.
9768                            // useProfileForDexopt = true;
9769                        }
9770                    } catch (Exception e) {
9771                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9772                                e);
9773                    }
9774                } else {
9775                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9776                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9777                    // minimize the number off apps being speed-profile compiled during first boot.
9778                    // The other paths will not change the filter.
9779                    if (disabledPs != null && disabledPs.pkg.isStub) {
9780                        // The package is the stub one, remove the stub suffix to get the normal
9781                        // package and APK names.
9782                        String systemProfilePath =
9783                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9784                        profileFile = new File(systemProfilePath);
9785                        // If we have a profile for a compressed APK, copy it to the reference
9786                        // location.
9787                        // Note that copying the profile here will cause it to override the
9788                        // reference profile every OTA even though the existing reference profile
9789                        // may have more data. We can't copy during decompression since the
9790                        // directories are not set up at that point.
9791                        if (profileFile.exists()) {
9792                            try {
9793                                // We could also do this lazily before calling dexopt in
9794                                // PackageDexOptimizer to prevent this happening on first boot. The
9795                                // issue is that we don't have a good way to say "do this only
9796                                // once".
9797                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9798                                        pkg.applicationInfo.uid, pkg.packageName)) {
9799                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9800                                } else {
9801                                    useProfileForDexopt = true;
9802                                }
9803                            } catch (Exception e) {
9804                                Log.e(TAG, "Failed to copy profile " +
9805                                        profileFile.getAbsolutePath() + " ", e);
9806                            }
9807                        }
9808                    }
9809                }
9810            }
9811
9812            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9813                if (DEBUG_DEXOPT) {
9814                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9815                }
9816                numberOfPackagesSkipped++;
9817                continue;
9818            }
9819
9820            if (DEBUG_DEXOPT) {
9821                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9822                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9823            }
9824
9825            if (showDialog) {
9826                try {
9827                    ActivityManager.getService().showBootMessage(
9828                            mContext.getResources().getString(R.string.android_upgrading_apk,
9829                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9830                } catch (RemoteException e) {
9831                }
9832                synchronized (mPackages) {
9833                    mDexOptDialogShown = true;
9834                }
9835            }
9836
9837            String pkgCompilerFilter = compilerFilter;
9838            if (useProfileForDexopt) {
9839                // Use background dexopt mode to try and use the profile. Note that this does not
9840                // guarantee usage of the profile.
9841                pkgCompilerFilter =
9842                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9843                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9844            }
9845
9846            // checkProfiles is false to avoid merging profiles during boot which
9847            // might interfere with background compilation (b/28612421).
9848            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9849            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9850            // trade-off worth doing to save boot time work.
9851            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9852            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9853                    pkg.packageName,
9854                    pkgCompilerFilter,
9855                    dexoptFlags));
9856
9857            switch (primaryDexOptStaus) {
9858                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9859                    numberOfPackagesOptimized++;
9860                    break;
9861                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9862                    numberOfPackagesSkipped++;
9863                    break;
9864                case PackageDexOptimizer.DEX_OPT_FAILED:
9865                    numberOfPackagesFailed++;
9866                    break;
9867                default:
9868                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9869                    break;
9870            }
9871        }
9872
9873        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9874                numberOfPackagesFailed };
9875    }
9876
9877    @Override
9878    public void notifyPackageUse(String packageName, int reason) {
9879        synchronized (mPackages) {
9880            final int callingUid = Binder.getCallingUid();
9881            final int callingUserId = UserHandle.getUserId(callingUid);
9882            if (getInstantAppPackageName(callingUid) != null) {
9883                if (!isCallerSameApp(packageName, callingUid)) {
9884                    return;
9885                }
9886            } else {
9887                if (isInstantApp(packageName, callingUserId)) {
9888                    return;
9889                }
9890            }
9891            notifyPackageUseLocked(packageName, reason);
9892        }
9893    }
9894
9895    private void notifyPackageUseLocked(String packageName, int reason) {
9896        final PackageParser.Package p = mPackages.get(packageName);
9897        if (p == null) {
9898            return;
9899        }
9900        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9901    }
9902
9903    @Override
9904    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9905            List<String> classPaths, String loaderIsa) {
9906        int userId = UserHandle.getCallingUserId();
9907        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9908        if (ai == null) {
9909            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9910                + loadingPackageName + ", user=" + userId);
9911            return;
9912        }
9913        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9914    }
9915
9916    @Override
9917    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9918            IDexModuleRegisterCallback callback) {
9919        int userId = UserHandle.getCallingUserId();
9920        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9921        DexManager.RegisterDexModuleResult result;
9922        if (ai == null) {
9923            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9924                     " calling user. package=" + packageName + ", user=" + userId);
9925            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9926        } else {
9927            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9928        }
9929
9930        if (callback != null) {
9931            mHandler.post(() -> {
9932                try {
9933                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9934                } catch (RemoteException e) {
9935                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9936                }
9937            });
9938        }
9939    }
9940
9941    /**
9942     * Ask the package manager to perform a dex-opt with the given compiler filter.
9943     *
9944     * Note: exposed only for the shell command to allow moving packages explicitly to a
9945     *       definite state.
9946     */
9947    @Override
9948    public boolean performDexOptMode(String packageName,
9949            boolean checkProfiles, String targetCompilerFilter, boolean force,
9950            boolean bootComplete, String splitName) {
9951        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9952                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9953                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9954        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9955                splitName, flags));
9956    }
9957
9958    /**
9959     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9960     * secondary dex files belonging to the given package.
9961     *
9962     * Note: exposed only for the shell command to allow moving packages explicitly to a
9963     *       definite state.
9964     */
9965    @Override
9966    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9967            boolean force) {
9968        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9969                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9970                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9971                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9972        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9973    }
9974
9975    /*package*/ boolean performDexOpt(DexoptOptions options) {
9976        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9977            return false;
9978        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9979            return false;
9980        }
9981
9982        if (options.isDexoptOnlySecondaryDex()) {
9983            return mDexManager.dexoptSecondaryDex(options);
9984        } else {
9985            int dexoptStatus = performDexOptWithStatus(options);
9986            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9987        }
9988    }
9989
9990    /**
9991     * Perform dexopt on the given package and return one of following result:
9992     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9993     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9994     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9995     */
9996    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9997        return performDexOptTraced(options);
9998    }
9999
10000    private int performDexOptTraced(DexoptOptions options) {
10001        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10002        try {
10003            return performDexOptInternal(options);
10004        } finally {
10005            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10006        }
10007    }
10008
10009    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
10010    // if the package can now be considered up to date for the given filter.
10011    private int performDexOptInternal(DexoptOptions options) {
10012        PackageParser.Package p;
10013        synchronized (mPackages) {
10014            p = mPackages.get(options.getPackageName());
10015            if (p == null) {
10016                // Package could not be found. Report failure.
10017                return PackageDexOptimizer.DEX_OPT_FAILED;
10018            }
10019            mPackageUsage.maybeWriteAsync(mPackages);
10020            mCompilerStats.maybeWriteAsync();
10021        }
10022        long callingId = Binder.clearCallingIdentity();
10023        try {
10024            synchronized (mInstallLock) {
10025                return performDexOptInternalWithDependenciesLI(p, options);
10026            }
10027        } finally {
10028            Binder.restoreCallingIdentity(callingId);
10029        }
10030    }
10031
10032    public ArraySet<String> getOptimizablePackages() {
10033        ArraySet<String> pkgs = new ArraySet<String>();
10034        synchronized (mPackages) {
10035            for (PackageParser.Package p : mPackages.values()) {
10036                if (PackageDexOptimizer.canOptimizePackage(p)) {
10037                    pkgs.add(p.packageName);
10038                }
10039            }
10040        }
10041        return pkgs;
10042    }
10043
10044    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
10045            DexoptOptions options) {
10046        // Select the dex optimizer based on the force parameter.
10047        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
10048        //       allocate an object here.
10049        PackageDexOptimizer pdo = options.isForce()
10050                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
10051                : mPackageDexOptimizer;
10052
10053        // Dexopt all dependencies first. Note: we ignore the return value and march on
10054        // on errors.
10055        // Note that we are going to call performDexOpt on those libraries as many times as
10056        // they are referenced in packages. When we do a batch of performDexOpt (for example
10057        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
10058        // and the first package that uses the library will dexopt it. The
10059        // others will see that the compiled code for the library is up to date.
10060        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
10061        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10062        if (!deps.isEmpty()) {
10063            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10064                    options.getCompilerFilter(), options.getSplitName(),
10065                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10066            for (PackageParser.Package depPackage : deps) {
10067                // TODO: Analyze and investigate if we (should) profile libraries.
10068                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10069                        getOrCreateCompilerPackageStats(depPackage),
10070                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10071            }
10072        }
10073        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10074                getOrCreateCompilerPackageStats(p),
10075                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10076    }
10077
10078    /**
10079     * Reconcile the information we have about the secondary dex files belonging to
10080     * {@code packagName} and the actual dex files. For all dex files that were
10081     * deleted, update the internal records and delete the generated oat files.
10082     */
10083    @Override
10084    public void reconcileSecondaryDexFiles(String packageName) {
10085        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10086            return;
10087        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10088            return;
10089        }
10090        mDexManager.reconcileSecondaryDexFiles(packageName);
10091    }
10092
10093    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10094    // a reference there.
10095    /*package*/ DexManager getDexManager() {
10096        return mDexManager;
10097    }
10098
10099    /**
10100     * Execute the background dexopt job immediately.
10101     */
10102    @Override
10103    public boolean runBackgroundDexoptJob() {
10104        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10105            return false;
10106        }
10107        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10108    }
10109
10110    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10111        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10112                || p.usesStaticLibraries != null) {
10113            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10114            Set<String> collectedNames = new HashSet<>();
10115            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10116
10117            retValue.remove(p);
10118
10119            return retValue;
10120        } else {
10121            return Collections.emptyList();
10122        }
10123    }
10124
10125    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10126            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10127        if (!collectedNames.contains(p.packageName)) {
10128            collectedNames.add(p.packageName);
10129            collected.add(p);
10130
10131            if (p.usesLibraries != null) {
10132                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10133                        null, collected, collectedNames);
10134            }
10135            if (p.usesOptionalLibraries != null) {
10136                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10137                        null, collected, collectedNames);
10138            }
10139            if (p.usesStaticLibraries != null) {
10140                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10141                        p.usesStaticLibrariesVersions, collected, collectedNames);
10142            }
10143        }
10144    }
10145
10146    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10147            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10148        final int libNameCount = libs.size();
10149        for (int i = 0; i < libNameCount; i++) {
10150            String libName = libs.get(i);
10151            int version = (versions != null && versions.length == libNameCount)
10152                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10153            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10154            if (libPkg != null) {
10155                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10156            }
10157        }
10158    }
10159
10160    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10161        synchronized (mPackages) {
10162            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10163            if (libEntry != null) {
10164                return mPackages.get(libEntry.apk);
10165            }
10166            return null;
10167        }
10168    }
10169
10170    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10171        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10172        if (versionedLib == null) {
10173            return null;
10174        }
10175        return versionedLib.get(version);
10176    }
10177
10178    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10179        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10180                pkg.staticSharedLibName);
10181        if (versionedLib == null) {
10182            return null;
10183        }
10184        int previousLibVersion = -1;
10185        final int versionCount = versionedLib.size();
10186        for (int i = 0; i < versionCount; i++) {
10187            final int libVersion = versionedLib.keyAt(i);
10188            if (libVersion < pkg.staticSharedLibVersion) {
10189                previousLibVersion = Math.max(previousLibVersion, libVersion);
10190            }
10191        }
10192        if (previousLibVersion >= 0) {
10193            return versionedLib.get(previousLibVersion);
10194        }
10195        return null;
10196    }
10197
10198    public void shutdown() {
10199        mPackageUsage.writeNow(mPackages);
10200        mCompilerStats.writeNow();
10201        mDexManager.writePackageDexUsageNow();
10202    }
10203
10204    @Override
10205    public void dumpProfiles(String packageName) {
10206        PackageParser.Package pkg;
10207        synchronized (mPackages) {
10208            pkg = mPackages.get(packageName);
10209            if (pkg == null) {
10210                throw new IllegalArgumentException("Unknown package: " + packageName);
10211            }
10212        }
10213        /* Only the shell, root, or the app user should be able to dump profiles. */
10214        int callingUid = Binder.getCallingUid();
10215        if (callingUid != Process.SHELL_UID &&
10216            callingUid != Process.ROOT_UID &&
10217            callingUid != pkg.applicationInfo.uid) {
10218            throw new SecurityException("dumpProfiles");
10219        }
10220
10221        synchronized (mInstallLock) {
10222            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10223            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10224            try {
10225                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10226                String codePaths = TextUtils.join(";", allCodePaths);
10227                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10228            } catch (InstallerException e) {
10229                Slog.w(TAG, "Failed to dump profiles", e);
10230            }
10231            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10232        }
10233    }
10234
10235    @Override
10236    public void forceDexOpt(String packageName) {
10237        enforceSystemOrRoot("forceDexOpt");
10238
10239        PackageParser.Package pkg;
10240        synchronized (mPackages) {
10241            pkg = mPackages.get(packageName);
10242            if (pkg == null) {
10243                throw new IllegalArgumentException("Unknown package: " + packageName);
10244            }
10245        }
10246
10247        synchronized (mInstallLock) {
10248            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10249
10250            // Whoever is calling forceDexOpt wants a compiled package.
10251            // Don't use profiles since that may cause compilation to be skipped.
10252            final int res = performDexOptInternalWithDependenciesLI(
10253                    pkg,
10254                    new DexoptOptions(packageName,
10255                            getDefaultCompilerFilter(),
10256                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10257
10258            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10259            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10260                throw new IllegalStateException("Failed to dexopt: " + res);
10261            }
10262        }
10263    }
10264
10265    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10266        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10267            Slog.w(TAG, "Unable to update from " + oldPkg.name
10268                    + " to " + newPkg.packageName
10269                    + ": old package not in system partition");
10270            return false;
10271        } else if (mPackages.get(oldPkg.name) != null) {
10272            Slog.w(TAG, "Unable to update from " + oldPkg.name
10273                    + " to " + newPkg.packageName
10274                    + ": old package still exists");
10275            return false;
10276        }
10277        return true;
10278    }
10279
10280    void removeCodePathLI(File codePath) {
10281        if (codePath.isDirectory()) {
10282            try {
10283                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10284            } catch (InstallerException e) {
10285                Slog.w(TAG, "Failed to remove code path", e);
10286            }
10287        } else {
10288            codePath.delete();
10289        }
10290    }
10291
10292    private int[] resolveUserIds(int userId) {
10293        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10294    }
10295
10296    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10297        if (pkg == null) {
10298            Slog.wtf(TAG, "Package was null!", new Throwable());
10299            return;
10300        }
10301        clearAppDataLeafLIF(pkg, userId, flags);
10302        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10303        for (int i = 0; i < childCount; i++) {
10304            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10305        }
10306    }
10307
10308    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10309        final PackageSetting ps;
10310        synchronized (mPackages) {
10311            ps = mSettings.mPackages.get(pkg.packageName);
10312        }
10313        for (int realUserId : resolveUserIds(userId)) {
10314            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10315            try {
10316                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10317                        ceDataInode);
10318            } catch (InstallerException e) {
10319                Slog.w(TAG, String.valueOf(e));
10320            }
10321        }
10322    }
10323
10324    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10325        if (pkg == null) {
10326            Slog.wtf(TAG, "Package was null!", new Throwable());
10327            return;
10328        }
10329        destroyAppDataLeafLIF(pkg, userId, flags);
10330        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10331        for (int i = 0; i < childCount; i++) {
10332            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10333        }
10334    }
10335
10336    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10337        final PackageSetting ps;
10338        synchronized (mPackages) {
10339            ps = mSettings.mPackages.get(pkg.packageName);
10340        }
10341        for (int realUserId : resolveUserIds(userId)) {
10342            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10343            try {
10344                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10345                        ceDataInode);
10346            } catch (InstallerException e) {
10347                Slog.w(TAG, String.valueOf(e));
10348            }
10349            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10350        }
10351    }
10352
10353    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10354        if (pkg == null) {
10355            Slog.wtf(TAG, "Package was null!", new Throwable());
10356            return;
10357        }
10358        destroyAppProfilesLeafLIF(pkg);
10359        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10360        for (int i = 0; i < childCount; i++) {
10361            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10362        }
10363    }
10364
10365    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10366        try {
10367            mInstaller.destroyAppProfiles(pkg.packageName);
10368        } catch (InstallerException e) {
10369            Slog.w(TAG, String.valueOf(e));
10370        }
10371    }
10372
10373    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10374        if (pkg == null) {
10375            Slog.wtf(TAG, "Package was null!", new Throwable());
10376            return;
10377        }
10378        clearAppProfilesLeafLIF(pkg);
10379        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10380        for (int i = 0; i < childCount; i++) {
10381            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10382        }
10383    }
10384
10385    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10386        try {
10387            mInstaller.clearAppProfiles(pkg.packageName);
10388        } catch (InstallerException e) {
10389            Slog.w(TAG, String.valueOf(e));
10390        }
10391    }
10392
10393    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10394            long lastUpdateTime) {
10395        // Set parent install/update time
10396        PackageSetting ps = (PackageSetting) pkg.mExtras;
10397        if (ps != null) {
10398            ps.firstInstallTime = firstInstallTime;
10399            ps.lastUpdateTime = lastUpdateTime;
10400        }
10401        // Set children install/update time
10402        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10403        for (int i = 0; i < childCount; i++) {
10404            PackageParser.Package childPkg = pkg.childPackages.get(i);
10405            ps = (PackageSetting) childPkg.mExtras;
10406            if (ps != null) {
10407                ps.firstInstallTime = firstInstallTime;
10408                ps.lastUpdateTime = lastUpdateTime;
10409            }
10410        }
10411    }
10412
10413    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
10414            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        // The collection used here must maintain the order of addition (so
10444        // that libraries are searched in the correct order) and must have no
10445        // duplicates.
10446        Set<String> usesLibraryFiles = null;
10447        if (pkg.usesLibraries != null) {
10448            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10449                    null, null, pkg.packageName, changingLib, true,
10450                    pkg.applicationInfo.targetSdkVersion, null);
10451        }
10452        if (pkg.usesStaticLibraries != null) {
10453            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10454                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10455                    pkg.packageName, changingLib, true,
10456                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10457        }
10458        if (pkg.usesOptionalLibraries != null) {
10459            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10460                    null, null, pkg.packageName, changingLib, false,
10461                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10462        }
10463        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10464            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10465        } else {
10466            pkg.usesLibraryFiles = null;
10467        }
10468    }
10469
10470    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10471            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10472            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10473            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
10474            throws PackageManagerException {
10475        final int libCount = requestedLibraries.size();
10476        for (int i = 0; i < libCount; i++) {
10477            final String libName = requestedLibraries.get(i);
10478            final int libVersion = requiredVersions != null ? requiredVersions[i]
10479                    : SharedLibraryInfo.VERSION_UNDEFINED;
10480            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10481            if (libEntry == null) {
10482                if (required) {
10483                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10484                            "Package " + packageName + " requires unavailable shared library "
10485                                    + libName + "; failing!");
10486                } else if (DEBUG_SHARED_LIBRARIES) {
10487                    Slog.i(TAG, "Package " + packageName
10488                            + " desires unavailable shared library "
10489                            + libName + "; ignoring!");
10490                }
10491            } else {
10492                if (requiredVersions != null && requiredCertDigests != null) {
10493                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10494                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10495                            "Package " + packageName + " requires unavailable static shared"
10496                                    + " library " + libName + " version "
10497                                    + libEntry.info.getVersion() + "; failing!");
10498                    }
10499
10500                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10501                    if (libPkg == null) {
10502                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10503                                "Package " + packageName + " requires unavailable static shared"
10504                                        + " library; failing!");
10505                    }
10506
10507                    final String[] expectedCertDigests = requiredCertDigests[i];
10508                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10509                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10510                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10511                            : PackageUtils.computeSignaturesSha256Digests(
10512                                    new Signature[]{libPkg.mSignatures[0]});
10513
10514                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10515                    // target O we don't parse the "additional-certificate" tags similarly
10516                    // how we only consider all certs only for apps targeting O (see above).
10517                    // Therefore, the size check is safe to make.
10518                    if (expectedCertDigests.length != libCertDigests.length) {
10519                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10520                                "Package " + packageName + " requires differently signed" +
10521                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10522                    }
10523
10524                    // Use a predictable order as signature order may vary
10525                    Arrays.sort(libCertDigests);
10526                    Arrays.sort(expectedCertDigests);
10527
10528                    final int certCount = libCertDigests.length;
10529                    for (int j = 0; j < certCount; j++) {
10530                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10531                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10532                                    "Package " + packageName + " requires differently signed" +
10533                                            " static shared library; failing!");
10534                        }
10535                    }
10536                }
10537
10538                if (outUsedLibraries == null) {
10539                    // Use LinkedHashSet to preserve the order of files added to
10540                    // usesLibraryFiles while eliminating duplicates.
10541                    outUsedLibraries = new LinkedHashSet<>();
10542                }
10543                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10544            }
10545        }
10546        return outUsedLibraries;
10547    }
10548
10549    private static boolean hasString(List<String> list, List<String> which) {
10550        if (list == null) {
10551            return false;
10552        }
10553        for (int i=list.size()-1; i>=0; i--) {
10554            for (int j=which.size()-1; j>=0; j--) {
10555                if (which.get(j).equals(list.get(i))) {
10556                    return true;
10557                }
10558            }
10559        }
10560        return false;
10561    }
10562
10563    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10564            PackageParser.Package changingPkg) {
10565        ArrayList<PackageParser.Package> res = null;
10566        for (PackageParser.Package pkg : mPackages.values()) {
10567            if (changingPkg != null
10568                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10569                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10570                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10571                            changingPkg.staticSharedLibName)) {
10572                return null;
10573            }
10574            if (res == null) {
10575                res = new ArrayList<>();
10576            }
10577            res.add(pkg);
10578            try {
10579                updateSharedLibrariesLPr(pkg, changingPkg);
10580            } catch (PackageManagerException e) {
10581                // If a system app update or an app and a required lib missing we
10582                // delete the package and for updated system apps keep the data as
10583                // it is better for the user to reinstall than to be in an limbo
10584                // state. Also libs disappearing under an app should never happen
10585                // - just in case.
10586                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10587                    final int flags = pkg.isUpdatedSystemApp()
10588                            ? PackageManager.DELETE_KEEP_DATA : 0;
10589                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10590                            flags , null, true, null);
10591                }
10592                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10593            }
10594        }
10595        return res;
10596    }
10597
10598    /**
10599     * Derive the value of the {@code cpuAbiOverride} based on the provided
10600     * value and an optional stored value from the package settings.
10601     */
10602    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10603        String cpuAbiOverride = null;
10604
10605        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10606            cpuAbiOverride = null;
10607        } else if (abiOverride != null) {
10608            cpuAbiOverride = abiOverride;
10609        } else if (settings != null) {
10610            cpuAbiOverride = settings.cpuAbiOverrideString;
10611        }
10612
10613        return cpuAbiOverride;
10614    }
10615
10616    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10617            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10618                    throws PackageManagerException {
10619        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10620        // If the package has children and this is the first dive in the function
10621        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10622        // whether all packages (parent and children) would be successfully scanned
10623        // before the actual scan since scanning mutates internal state and we want
10624        // to atomically install the package and its children.
10625        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10626            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10627                scanFlags |= SCAN_CHECK_ONLY;
10628            }
10629        } else {
10630            scanFlags &= ~SCAN_CHECK_ONLY;
10631        }
10632
10633        final PackageParser.Package scannedPkg;
10634        try {
10635            // Scan the parent
10636            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10637            // Scan the children
10638            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10639            for (int i = 0; i < childCount; i++) {
10640                PackageParser.Package childPkg = pkg.childPackages.get(i);
10641                scanPackageLI(childPkg, policyFlags,
10642                        scanFlags, currentTime, user);
10643            }
10644        } finally {
10645            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10646        }
10647
10648        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10649            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10650        }
10651
10652        return scannedPkg;
10653    }
10654
10655    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10656            int scanFlags, long currentTime, @Nullable UserHandle user)
10657                    throws PackageManagerException {
10658        boolean success = false;
10659        try {
10660            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10661                    currentTime, user);
10662            success = true;
10663            return res;
10664        } finally {
10665            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10666                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10667                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10668                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10669                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10670            }
10671        }
10672    }
10673
10674    /**
10675     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10676     */
10677    private static boolean apkHasCode(String fileName) {
10678        StrictJarFile jarFile = null;
10679        try {
10680            jarFile = new StrictJarFile(fileName,
10681                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10682            return jarFile.findEntry("classes.dex") != null;
10683        } catch (IOException ignore) {
10684        } finally {
10685            try {
10686                if (jarFile != null) {
10687                    jarFile.close();
10688                }
10689            } catch (IOException ignore) {}
10690        }
10691        return false;
10692    }
10693
10694    /**
10695     * Enforces code policy for the package. This ensures that if an APK has
10696     * declared hasCode="true" in its manifest that the APK actually contains
10697     * code.
10698     *
10699     * @throws PackageManagerException If bytecode could not be found when it should exist
10700     */
10701    private static void assertCodePolicy(PackageParser.Package pkg)
10702            throws PackageManagerException {
10703        final boolean shouldHaveCode =
10704                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10705        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10706            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10707                    "Package " + pkg.baseCodePath + " code is missing");
10708        }
10709
10710        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10711            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10712                final boolean splitShouldHaveCode =
10713                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10714                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10715                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10716                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10717                }
10718            }
10719        }
10720    }
10721
10722    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10723            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10724                    throws PackageManagerException {
10725        if (DEBUG_PACKAGE_SCANNING) {
10726            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10727                Log.d(TAG, "Scanning package " + pkg.packageName);
10728        }
10729
10730        applyPolicy(pkg, policyFlags);
10731
10732        assertPackageIsValid(pkg, policyFlags, scanFlags);
10733
10734        if (Build.IS_DEBUGGABLE &&
10735                pkg.isPrivilegedApp() &&
10736                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10737            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10738        }
10739
10740        // Initialize package source and resource directories
10741        final File scanFile = new File(pkg.codePath);
10742        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10743        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10744
10745        SharedUserSetting suid = null;
10746        PackageSetting pkgSetting = null;
10747
10748        // Getting the package setting may have a side-effect, so if we
10749        // are only checking if scan would succeed, stash a copy of the
10750        // old setting to restore at the end.
10751        PackageSetting nonMutatedPs = null;
10752
10753        // We keep references to the derived CPU Abis from settings in oder to reuse
10754        // them in the case where we're not upgrading or booting for the first time.
10755        String primaryCpuAbiFromSettings = null;
10756        String secondaryCpuAbiFromSettings = null;
10757        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10758
10759        // writer
10760        synchronized (mPackages) {
10761            if (pkg.mSharedUserId != null) {
10762                // SIDE EFFECTS; may potentially allocate a new shared user
10763                suid = mSettings.getSharedUserLPw(
10764                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10765                if (DEBUG_PACKAGE_SCANNING) {
10766                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10767                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10768                                + "): packages=" + suid.packages);
10769                }
10770            }
10771
10772            // Check if we are renaming from an original package name.
10773            PackageSetting origPackage = null;
10774            String realName = null;
10775            if (pkg.mOriginalPackages != null) {
10776                // This package may need to be renamed to a previously
10777                // installed name.  Let's check on that...
10778                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10779                if (pkg.mOriginalPackages.contains(renamed)) {
10780                    // This package had originally been installed as the
10781                    // original name, and we have already taken care of
10782                    // transitioning to the new one.  Just update the new
10783                    // one to continue using the old name.
10784                    realName = pkg.mRealPackage;
10785                    if (!pkg.packageName.equals(renamed)) {
10786                        // Callers into this function may have already taken
10787                        // care of renaming the package; only do it here if
10788                        // it is not already done.
10789                        pkg.setPackageName(renamed);
10790                    }
10791                } else {
10792                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10793                        if ((origPackage = mSettings.getPackageLPr(
10794                                pkg.mOriginalPackages.get(i))) != null) {
10795                            // We do have the package already installed under its
10796                            // original name...  should we use it?
10797                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10798                                // New package is not compatible with original.
10799                                origPackage = null;
10800                                continue;
10801                            } else if (origPackage.sharedUser != null) {
10802                                // Make sure uid is compatible between packages.
10803                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10804                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10805                                            + " to " + pkg.packageName + ": old uid "
10806                                            + origPackage.sharedUser.name
10807                                            + " differs from " + pkg.mSharedUserId);
10808                                    origPackage = null;
10809                                    continue;
10810                                }
10811                                // TODO: Add case when shared user id is added [b/28144775]
10812                            } else {
10813                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10814                                        + pkg.packageName + " to old name " + origPackage.name);
10815                            }
10816                            break;
10817                        }
10818                    }
10819                }
10820            }
10821
10822            if (mTransferedPackages.contains(pkg.packageName)) {
10823                Slog.w(TAG, "Package " + pkg.packageName
10824                        + " was transferred to another, but its .apk remains");
10825            }
10826
10827            // See comments in nonMutatedPs declaration
10828            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10829                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10830                if (foundPs != null) {
10831                    nonMutatedPs = new PackageSetting(foundPs);
10832                }
10833            }
10834
10835            if (!needToDeriveAbi) {
10836                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10837                if (foundPs != null) {
10838                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10839                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10840                } else {
10841                    // when re-adding a system package failed after uninstalling updates.
10842                    needToDeriveAbi = true;
10843                }
10844            }
10845
10846            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10847            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10848                PackageManagerService.reportSettingsProblem(Log.WARN,
10849                        "Package " + pkg.packageName + " shared user changed from "
10850                                + (pkgSetting.sharedUser != null
10851                                        ? pkgSetting.sharedUser.name : "<nothing>")
10852                                + " to "
10853                                + (suid != null ? suid.name : "<nothing>")
10854                                + "; replacing with new");
10855                pkgSetting = null;
10856            }
10857            final PackageSetting oldPkgSetting =
10858                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10859            final PackageSetting disabledPkgSetting =
10860                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10861
10862            String[] usesStaticLibraries = null;
10863            if (pkg.usesStaticLibraries != null) {
10864                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10865                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10866            }
10867
10868            if (pkgSetting == null) {
10869                final String parentPackageName = (pkg.parentPackage != null)
10870                        ? pkg.parentPackage.packageName : null;
10871                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10872                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10873                // REMOVE SharedUserSetting from method; update in a separate call
10874                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10875                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10876                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10877                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10878                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10879                        true /*allowInstall*/, instantApp, virtualPreload,
10880                        parentPackageName, pkg.getChildPackageNames(),
10881                        UserManagerService.getInstance(), usesStaticLibraries,
10882                        pkg.usesStaticLibrariesVersions);
10883                // SIDE EFFECTS; updates system state; move elsewhere
10884                if (origPackage != null) {
10885                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10886                }
10887                mSettings.addUserToSettingLPw(pkgSetting);
10888            } else {
10889                // REMOVE SharedUserSetting from method; update in a separate call.
10890                //
10891                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10892                // secondaryCpuAbi are not known at this point so we always update them
10893                // to null here, only to reset them at a later point.
10894                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10895                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10896                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10897                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10898                        UserManagerService.getInstance(), usesStaticLibraries,
10899                        pkg.usesStaticLibrariesVersions);
10900            }
10901            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10902            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10903
10904            // SIDE EFFECTS; modifies system state; move elsewhere
10905            if (pkgSetting.origPackage != null) {
10906                // If we are first transitioning from an original package,
10907                // fix up the new package's name now.  We need to do this after
10908                // looking up the package under its new name, so getPackageLP
10909                // can take care of fiddling things correctly.
10910                pkg.setPackageName(origPackage.name);
10911
10912                // File a report about this.
10913                String msg = "New package " + pkgSetting.realName
10914                        + " renamed to replace old package " + pkgSetting.name;
10915                reportSettingsProblem(Log.WARN, msg);
10916
10917                // Make a note of it.
10918                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10919                    mTransferedPackages.add(origPackage.name);
10920                }
10921
10922                // No longer need to retain this.
10923                pkgSetting.origPackage = null;
10924            }
10925
10926            // SIDE EFFECTS; modifies system state; move elsewhere
10927            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10928                // Make a note of it.
10929                mTransferedPackages.add(pkg.packageName);
10930            }
10931
10932            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10933                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10934            }
10935
10936            if ((scanFlags & SCAN_BOOTING) == 0
10937                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10938                // Check all shared libraries and map to their actual file path.
10939                // We only do this here for apps not on a system dir, because those
10940                // are the only ones that can fail an install due to this.  We
10941                // will take care of the system apps by updating all of their
10942                // library paths after the scan is done. Also during the initial
10943                // scan don't update any libs as we do this wholesale after all
10944                // apps are scanned to avoid dependency based scanning.
10945                updateSharedLibrariesLPr(pkg, null);
10946            }
10947
10948            if (mFoundPolicyFile) {
10949                SELinuxMMAC.assignSeInfoValue(pkg);
10950            }
10951            pkg.applicationInfo.uid = pkgSetting.appId;
10952            pkg.mExtras = pkgSetting;
10953
10954
10955            // Static shared libs have same package with different versions where
10956            // we internally use a synthetic package name to allow multiple versions
10957            // of the same package, therefore we need to compare signatures against
10958            // the package setting for the latest library version.
10959            PackageSetting signatureCheckPs = pkgSetting;
10960            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10961                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10962                if (libraryEntry != null) {
10963                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10964                }
10965            }
10966
10967            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10968                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10969                    // We just determined the app is signed correctly, so bring
10970                    // over the latest parsed certs.
10971                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10972                } else {
10973                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10974                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10975                                "Package " + pkg.packageName + " upgrade keys do not match the "
10976                                + "previously installed version");
10977                    } else {
10978                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10979                        String msg = "System package " + pkg.packageName
10980                                + " signature changed; retaining data.";
10981                        reportSettingsProblem(Log.WARN, msg);
10982                    }
10983                }
10984            } else {
10985                try {
10986                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10987                    verifySignaturesLP(signatureCheckPs, pkg);
10988                    // We just determined the app is signed correctly, so bring
10989                    // over the latest parsed certs.
10990                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10991                } catch (PackageManagerException e) {
10992                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10993                        throw e;
10994                    }
10995                    // The signature has changed, but this package is in the system
10996                    // image...  let's recover!
10997                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10998                    // However...  if this package is part of a shared user, but it
10999                    // doesn't match the signature of the shared user, let's fail.
11000                    // What this means is that you can't change the signatures
11001                    // associated with an overall shared user, which doesn't seem all
11002                    // that unreasonable.
11003                    if (signatureCheckPs.sharedUser != null) {
11004                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
11005                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
11006                            throw new PackageManagerException(
11007                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
11008                                    "Signature mismatch for shared user: "
11009                                            + pkgSetting.sharedUser);
11010                        }
11011                    }
11012                    // File a report about this.
11013                    String msg = "System package " + pkg.packageName
11014                            + " signature changed; retaining data.";
11015                    reportSettingsProblem(Log.WARN, msg);
11016                }
11017            }
11018
11019            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
11020                // This package wants to adopt ownership of permissions from
11021                // another package.
11022                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
11023                    final String origName = pkg.mAdoptPermissions.get(i);
11024                    final PackageSetting orig = mSettings.getPackageLPr(origName);
11025                    if (orig != null) {
11026                        if (verifyPackageUpdateLPr(orig, pkg)) {
11027                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
11028                                    + pkg.packageName);
11029                            // SIDE EFFECTS; updates permissions system state; move elsewhere
11030                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
11031                        }
11032                    }
11033                }
11034            }
11035        }
11036
11037        pkg.applicationInfo.processName = fixProcessName(
11038                pkg.applicationInfo.packageName,
11039                pkg.applicationInfo.processName);
11040
11041        if (pkg != mPlatformPackage) {
11042            // Get all of our default paths setup
11043            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
11044        }
11045
11046        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
11047
11048        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
11049            if (needToDeriveAbi) {
11050                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
11051                final boolean extractNativeLibs = !pkg.isLibrary();
11052                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
11053                        mAppLib32InstallDir);
11054                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11055
11056                // Some system apps still use directory structure for native libraries
11057                // in which case we might end up not detecting abi solely based on apk
11058                // structure. Try to detect abi based on directory structure.
11059                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
11060                        pkg.applicationInfo.primaryCpuAbi == null) {
11061                    setBundledAppAbisAndRoots(pkg, pkgSetting);
11062                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11063                }
11064            } else {
11065                // This is not a first boot or an upgrade, don't bother deriving the
11066                // ABI during the scan. Instead, trust the value that was stored in the
11067                // package setting.
11068                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
11069                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
11070
11071                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11072
11073                if (DEBUG_ABI_SELECTION) {
11074                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11075                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11076                        pkg.applicationInfo.secondaryCpuAbi);
11077                }
11078            }
11079        } else {
11080            if ((scanFlags & SCAN_MOVE) != 0) {
11081                // We haven't run dex-opt for this move (since we've moved the compiled output too)
11082                // but we already have this packages package info in the PackageSetting. We just
11083                // use that and derive the native library path based on the new codepath.
11084                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11085                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11086            }
11087
11088            // Set native library paths again. For moves, the path will be updated based on the
11089            // ABIs we've determined above. For non-moves, the path will be updated based on the
11090            // ABIs we determined during compilation, but the path will depend on the final
11091            // package path (after the rename away from the stage path).
11092            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11093        }
11094
11095        // This is a special case for the "system" package, where the ABI is
11096        // dictated by the zygote configuration (and init.rc). We should keep track
11097        // of this ABI so that we can deal with "normal" applications that run under
11098        // the same UID correctly.
11099        if (mPlatformPackage == pkg) {
11100            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11101                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11102        }
11103
11104        // If there's a mismatch between the abi-override in the package setting
11105        // and the abiOverride specified for the install. Warn about this because we
11106        // would've already compiled the app without taking the package setting into
11107        // account.
11108        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11109            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11110                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11111                        " for package " + pkg.packageName);
11112            }
11113        }
11114
11115        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11116        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11117        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11118
11119        // Copy the derived override back to the parsed package, so that we can
11120        // update the package settings accordingly.
11121        pkg.cpuAbiOverride = cpuAbiOverride;
11122
11123        if (DEBUG_ABI_SELECTION) {
11124            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11125                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11126                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11127        }
11128
11129        // Push the derived path down into PackageSettings so we know what to
11130        // clean up at uninstall time.
11131        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11132
11133        if (DEBUG_ABI_SELECTION) {
11134            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11135                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11136                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11137        }
11138
11139        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11140        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11141            // We don't do this here during boot because we can do it all
11142            // at once after scanning all existing packages.
11143            //
11144            // We also do this *before* we perform dexopt on this package, so that
11145            // we can avoid redundant dexopts, and also to make sure we've got the
11146            // code and package path correct.
11147            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11148        }
11149
11150        if (mFactoryTest && pkg.requestedPermissions.contains(
11151                android.Manifest.permission.FACTORY_TEST)) {
11152            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11153        }
11154
11155        if (isSystemApp(pkg)) {
11156            pkgSetting.isOrphaned = true;
11157        }
11158
11159        // Take care of first install / last update times.
11160        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11161        if (currentTime != 0) {
11162            if (pkgSetting.firstInstallTime == 0) {
11163                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11164            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11165                pkgSetting.lastUpdateTime = currentTime;
11166            }
11167        } else if (pkgSetting.firstInstallTime == 0) {
11168            // We need *something*.  Take time time stamp of the file.
11169            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11170        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11171            if (scanFileTime != pkgSetting.timeStamp) {
11172                // A package on the system image has changed; consider this
11173                // to be an update.
11174                pkgSetting.lastUpdateTime = scanFileTime;
11175            }
11176        }
11177        pkgSetting.setTimeStamp(scanFileTime);
11178
11179        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11180            if (nonMutatedPs != null) {
11181                synchronized (mPackages) {
11182                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11183                }
11184            }
11185        } else {
11186            final int userId = user == null ? 0 : user.getIdentifier();
11187            // Modify state for the given package setting
11188            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11189                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11190            if (pkgSetting.getInstantApp(userId)) {
11191                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11192            }
11193        }
11194        return pkg;
11195    }
11196
11197    /**
11198     * Applies policy to the parsed package based upon the given policy flags.
11199     * Ensures the package is in a good state.
11200     * <p>
11201     * Implementation detail: This method must NOT have any side effect. It would
11202     * ideally be static, but, it requires locks to read system state.
11203     */
11204    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11205        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11206            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11207            if (pkg.applicationInfo.isDirectBootAware()) {
11208                // we're direct boot aware; set for all components
11209                for (PackageParser.Service s : pkg.services) {
11210                    s.info.encryptionAware = s.info.directBootAware = true;
11211                }
11212                for (PackageParser.Provider p : pkg.providers) {
11213                    p.info.encryptionAware = p.info.directBootAware = true;
11214                }
11215                for (PackageParser.Activity a : pkg.activities) {
11216                    a.info.encryptionAware = a.info.directBootAware = true;
11217                }
11218                for (PackageParser.Activity r : pkg.receivers) {
11219                    r.info.encryptionAware = r.info.directBootAware = true;
11220                }
11221            }
11222            if (compressedFileExists(pkg.codePath)) {
11223                pkg.isStub = true;
11224            }
11225        } else {
11226            // Only allow system apps to be flagged as core apps.
11227            pkg.coreApp = false;
11228            // clear flags not applicable to regular apps
11229            pkg.applicationInfo.privateFlags &=
11230                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11231            pkg.applicationInfo.privateFlags &=
11232                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11233        }
11234        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11235
11236        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11237            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11238        }
11239
11240        if (!isSystemApp(pkg)) {
11241            // Only system apps can use these features.
11242            pkg.mOriginalPackages = null;
11243            pkg.mRealPackage = null;
11244            pkg.mAdoptPermissions = null;
11245        }
11246    }
11247
11248    /**
11249     * Asserts the parsed package is valid according to the given policy. If the
11250     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11251     * <p>
11252     * Implementation detail: This method must NOT have any side effects. It would
11253     * ideally be static, but, it requires locks to read system state.
11254     *
11255     * @throws PackageManagerException If the package fails any of the validation checks
11256     */
11257    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11258            throws PackageManagerException {
11259        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11260            assertCodePolicy(pkg);
11261        }
11262
11263        if (pkg.applicationInfo.getCodePath() == null ||
11264                pkg.applicationInfo.getResourcePath() == null) {
11265            // Bail out. The resource and code paths haven't been set.
11266            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11267                    "Code and resource paths haven't been set correctly");
11268        }
11269
11270        // Make sure we're not adding any bogus keyset info
11271        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11272        ksms.assertScannedPackageValid(pkg);
11273
11274        synchronized (mPackages) {
11275            // The special "android" package can only be defined once
11276            if (pkg.packageName.equals("android")) {
11277                if (mAndroidApplication != null) {
11278                    Slog.w(TAG, "*************************************************");
11279                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11280                    Slog.w(TAG, " codePath=" + pkg.codePath);
11281                    Slog.w(TAG, "*************************************************");
11282                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11283                            "Core android package being redefined.  Skipping.");
11284                }
11285            }
11286
11287            // A package name must be unique; don't allow duplicates
11288            if (mPackages.containsKey(pkg.packageName)) {
11289                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11290                        "Application package " + pkg.packageName
11291                        + " already installed.  Skipping duplicate.");
11292            }
11293
11294            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11295                // Static libs have a synthetic package name containing the version
11296                // but we still want the base name to be unique.
11297                if (mPackages.containsKey(pkg.manifestPackageName)) {
11298                    throw new PackageManagerException(
11299                            "Duplicate static shared lib provider package");
11300                }
11301
11302                // Static shared libraries should have at least O target SDK
11303                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11304                    throw new PackageManagerException(
11305                            "Packages declaring static-shared libs must target O SDK or higher");
11306                }
11307
11308                // Package declaring static a shared lib cannot be instant apps
11309                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11310                    throw new PackageManagerException(
11311                            "Packages declaring static-shared libs cannot be instant apps");
11312                }
11313
11314                // Package declaring static a shared lib cannot be renamed since the package
11315                // name is synthetic and apps can't code around package manager internals.
11316                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11317                    throw new PackageManagerException(
11318                            "Packages declaring static-shared libs cannot be renamed");
11319                }
11320
11321                // Package declaring static a shared lib cannot declare child packages
11322                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11323                    throw new PackageManagerException(
11324                            "Packages declaring static-shared libs cannot have child packages");
11325                }
11326
11327                // Package declaring static a shared lib cannot declare dynamic libs
11328                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11329                    throw new PackageManagerException(
11330                            "Packages declaring static-shared libs cannot declare dynamic libs");
11331                }
11332
11333                // Package declaring static a shared lib cannot declare shared users
11334                if (pkg.mSharedUserId != null) {
11335                    throw new PackageManagerException(
11336                            "Packages declaring static-shared libs cannot declare shared users");
11337                }
11338
11339                // Static shared libs cannot declare activities
11340                if (!pkg.activities.isEmpty()) {
11341                    throw new PackageManagerException(
11342                            "Static shared libs cannot declare activities");
11343                }
11344
11345                // Static shared libs cannot declare services
11346                if (!pkg.services.isEmpty()) {
11347                    throw new PackageManagerException(
11348                            "Static shared libs cannot declare services");
11349                }
11350
11351                // Static shared libs cannot declare providers
11352                if (!pkg.providers.isEmpty()) {
11353                    throw new PackageManagerException(
11354                            "Static shared libs cannot declare content providers");
11355                }
11356
11357                // Static shared libs cannot declare receivers
11358                if (!pkg.receivers.isEmpty()) {
11359                    throw new PackageManagerException(
11360                            "Static shared libs cannot declare broadcast receivers");
11361                }
11362
11363                // Static shared libs cannot declare permission groups
11364                if (!pkg.permissionGroups.isEmpty()) {
11365                    throw new PackageManagerException(
11366                            "Static shared libs cannot declare permission groups");
11367                }
11368
11369                // Static shared libs cannot declare permissions
11370                if (!pkg.permissions.isEmpty()) {
11371                    throw new PackageManagerException(
11372                            "Static shared libs cannot declare permissions");
11373                }
11374
11375                // Static shared libs cannot declare protected broadcasts
11376                if (pkg.protectedBroadcasts != null) {
11377                    throw new PackageManagerException(
11378                            "Static shared libs cannot declare protected broadcasts");
11379                }
11380
11381                // Static shared libs cannot be overlay targets
11382                if (pkg.mOverlayTarget != null) {
11383                    throw new PackageManagerException(
11384                            "Static shared libs cannot be overlay targets");
11385                }
11386
11387                // The version codes must be ordered as lib versions
11388                int minVersionCode = Integer.MIN_VALUE;
11389                int maxVersionCode = Integer.MAX_VALUE;
11390
11391                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11392                        pkg.staticSharedLibName);
11393                if (versionedLib != null) {
11394                    final int versionCount = versionedLib.size();
11395                    for (int i = 0; i < versionCount; i++) {
11396                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11397                        final int libVersionCode = libInfo.getDeclaringPackage()
11398                                .getVersionCode();
11399                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11400                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11401                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11402                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11403                        } else {
11404                            minVersionCode = maxVersionCode = libVersionCode;
11405                            break;
11406                        }
11407                    }
11408                }
11409                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11410                    throw new PackageManagerException("Static shared"
11411                            + " lib version codes must be ordered as lib versions");
11412                }
11413            }
11414
11415            // Only privileged apps and updated privileged apps can add child packages.
11416            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11417                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11418                    throw new PackageManagerException("Only privileged apps can add child "
11419                            + "packages. Ignoring package " + pkg.packageName);
11420                }
11421                final int childCount = pkg.childPackages.size();
11422                for (int i = 0; i < childCount; i++) {
11423                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11424                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11425                            childPkg.packageName)) {
11426                        throw new PackageManagerException("Can't override child of "
11427                                + "another disabled app. Ignoring package " + pkg.packageName);
11428                    }
11429                }
11430            }
11431
11432            // If we're only installing presumed-existing packages, require that the
11433            // scanned APK is both already known and at the path previously established
11434            // for it.  Previously unknown packages we pick up normally, but if we have an
11435            // a priori expectation about this package's install presence, enforce it.
11436            // With a singular exception for new system packages. When an OTA contains
11437            // a new system package, we allow the codepath to change from a system location
11438            // to the user-installed location. If we don't allow this change, any newer,
11439            // user-installed version of the application will be ignored.
11440            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11441                if (mExpectingBetter.containsKey(pkg.packageName)) {
11442                    logCriticalInfo(Log.WARN,
11443                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11444                } else {
11445                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11446                    if (known != null) {
11447                        if (DEBUG_PACKAGE_SCANNING) {
11448                            Log.d(TAG, "Examining " + pkg.codePath
11449                                    + " and requiring known paths " + known.codePathString
11450                                    + " & " + known.resourcePathString);
11451                        }
11452                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11453                                || !pkg.applicationInfo.getResourcePath().equals(
11454                                        known.resourcePathString)) {
11455                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11456                                    "Application package " + pkg.packageName
11457                                    + " found at " + pkg.applicationInfo.getCodePath()
11458                                    + " but expected at " + known.codePathString
11459                                    + "; ignoring.");
11460                        }
11461                    } else {
11462                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11463                                "Application package " + pkg.packageName
11464                                + " not found; ignoring.");
11465                    }
11466                }
11467            }
11468
11469            // Verify that this new package doesn't have any content providers
11470            // that conflict with existing packages.  Only do this if the
11471            // package isn't already installed, since we don't want to break
11472            // things that are installed.
11473            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11474                final int N = pkg.providers.size();
11475                int i;
11476                for (i=0; i<N; i++) {
11477                    PackageParser.Provider p = pkg.providers.get(i);
11478                    if (p.info.authority != null) {
11479                        String names[] = p.info.authority.split(";");
11480                        for (int j = 0; j < names.length; j++) {
11481                            if (mProvidersByAuthority.containsKey(names[j])) {
11482                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11483                                final String otherPackageName =
11484                                        ((other != null && other.getComponentName() != null) ?
11485                                                other.getComponentName().getPackageName() : "?");
11486                                throw new PackageManagerException(
11487                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11488                                        "Can't install because provider name " + names[j]
11489                                                + " (in package " + pkg.applicationInfo.packageName
11490                                                + ") is already used by " + otherPackageName);
11491                            }
11492                        }
11493                    }
11494                }
11495            }
11496        }
11497    }
11498
11499    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11500            int type, String declaringPackageName, int declaringVersionCode) {
11501        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11502        if (versionedLib == null) {
11503            versionedLib = new SparseArray<>();
11504            mSharedLibraries.put(name, versionedLib);
11505            if (type == SharedLibraryInfo.TYPE_STATIC) {
11506                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11507            }
11508        } else if (versionedLib.indexOfKey(version) >= 0) {
11509            return false;
11510        }
11511        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11512                version, type, declaringPackageName, declaringVersionCode);
11513        versionedLib.put(version, libEntry);
11514        return true;
11515    }
11516
11517    private boolean removeSharedLibraryLPw(String name, int version) {
11518        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11519        if (versionedLib == null) {
11520            return false;
11521        }
11522        final int libIdx = versionedLib.indexOfKey(version);
11523        if (libIdx < 0) {
11524            return false;
11525        }
11526        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11527        versionedLib.remove(version);
11528        if (versionedLib.size() <= 0) {
11529            mSharedLibraries.remove(name);
11530            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11531                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11532                        .getPackageName());
11533            }
11534        }
11535        return true;
11536    }
11537
11538    /**
11539     * Adds a scanned package to the system. When this method is finished, the package will
11540     * be available for query, resolution, etc...
11541     */
11542    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11543            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11544        final String pkgName = pkg.packageName;
11545        if (mCustomResolverComponentName != null &&
11546                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11547            setUpCustomResolverActivity(pkg);
11548        }
11549
11550        if (pkg.packageName.equals("android")) {
11551            synchronized (mPackages) {
11552                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11553                    // Set up information for our fall-back user intent resolution activity.
11554                    mPlatformPackage = pkg;
11555                    pkg.mVersionCode = mSdkVersion;
11556                    mAndroidApplication = pkg.applicationInfo;
11557                    if (!mResolverReplaced) {
11558                        mResolveActivity.applicationInfo = mAndroidApplication;
11559                        mResolveActivity.name = ResolverActivity.class.getName();
11560                        mResolveActivity.packageName = mAndroidApplication.packageName;
11561                        mResolveActivity.processName = "system:ui";
11562                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11563                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11564                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11565                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11566                        mResolveActivity.exported = true;
11567                        mResolveActivity.enabled = true;
11568                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11569                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11570                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11571                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11572                                | ActivityInfo.CONFIG_ORIENTATION
11573                                | ActivityInfo.CONFIG_KEYBOARD
11574                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11575                        mResolveInfo.activityInfo = mResolveActivity;
11576                        mResolveInfo.priority = 0;
11577                        mResolveInfo.preferredOrder = 0;
11578                        mResolveInfo.match = 0;
11579                        mResolveComponentName = new ComponentName(
11580                                mAndroidApplication.packageName, mResolveActivity.name);
11581                    }
11582                }
11583            }
11584        }
11585
11586        ArrayList<PackageParser.Package> clientLibPkgs = null;
11587        // writer
11588        synchronized (mPackages) {
11589            boolean hasStaticSharedLibs = false;
11590
11591            // Any app can add new static shared libraries
11592            if (pkg.staticSharedLibName != null) {
11593                // Static shared libs don't allow renaming as they have synthetic package
11594                // names to allow install of multiple versions, so use name from manifest.
11595                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11596                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11597                        pkg.manifestPackageName, pkg.mVersionCode)) {
11598                    hasStaticSharedLibs = true;
11599                } else {
11600                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11601                                + pkg.staticSharedLibName + " already exists; skipping");
11602                }
11603                // Static shared libs cannot be updated once installed since they
11604                // use synthetic package name which includes the version code, so
11605                // not need to update other packages's shared lib dependencies.
11606            }
11607
11608            if (!hasStaticSharedLibs
11609                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11610                // Only system apps can add new dynamic shared libraries.
11611                if (pkg.libraryNames != null) {
11612                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11613                        String name = pkg.libraryNames.get(i);
11614                        boolean allowed = false;
11615                        if (pkg.isUpdatedSystemApp()) {
11616                            // New library entries can only be added through the
11617                            // system image.  This is important to get rid of a lot
11618                            // of nasty edge cases: for example if we allowed a non-
11619                            // system update of the app to add a library, then uninstalling
11620                            // the update would make the library go away, and assumptions
11621                            // we made such as through app install filtering would now
11622                            // have allowed apps on the device which aren't compatible
11623                            // with it.  Better to just have the restriction here, be
11624                            // conservative, and create many fewer cases that can negatively
11625                            // impact the user experience.
11626                            final PackageSetting sysPs = mSettings
11627                                    .getDisabledSystemPkgLPr(pkg.packageName);
11628                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11629                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11630                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11631                                        allowed = true;
11632                                        break;
11633                                    }
11634                                }
11635                            }
11636                        } else {
11637                            allowed = true;
11638                        }
11639                        if (allowed) {
11640                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11641                                    SharedLibraryInfo.VERSION_UNDEFINED,
11642                                    SharedLibraryInfo.TYPE_DYNAMIC,
11643                                    pkg.packageName, pkg.mVersionCode)) {
11644                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11645                                        + name + " already exists; skipping");
11646                            }
11647                        } else {
11648                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11649                                    + name + " that is not declared on system image; skipping");
11650                        }
11651                    }
11652
11653                    if ((scanFlags & SCAN_BOOTING) == 0) {
11654                        // If we are not booting, we need to update any applications
11655                        // that are clients of our shared library.  If we are booting,
11656                        // this will all be done once the scan is complete.
11657                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11658                    }
11659                }
11660            }
11661        }
11662
11663        if ((scanFlags & SCAN_BOOTING) != 0) {
11664            // No apps can run during boot scan, so they don't need to be frozen
11665        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11666            // Caller asked to not kill app, so it's probably not frozen
11667        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11668            // Caller asked us to ignore frozen check for some reason; they
11669            // probably didn't know the package name
11670        } else {
11671            // We're doing major surgery on this package, so it better be frozen
11672            // right now to keep it from launching
11673            checkPackageFrozen(pkgName);
11674        }
11675
11676        // Also need to kill any apps that are dependent on the library.
11677        if (clientLibPkgs != null) {
11678            for (int i=0; i<clientLibPkgs.size(); i++) {
11679                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11680                killApplication(clientPkg.applicationInfo.packageName,
11681                        clientPkg.applicationInfo.uid, "update lib");
11682            }
11683        }
11684
11685        // writer
11686        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11687
11688        synchronized (mPackages) {
11689            // We don't expect installation to fail beyond this point
11690
11691            // Add the new setting to mSettings
11692            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11693            // Add the new setting to mPackages
11694            mPackages.put(pkg.applicationInfo.packageName, pkg);
11695            // Make sure we don't accidentally delete its data.
11696            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11697            while (iter.hasNext()) {
11698                PackageCleanItem item = iter.next();
11699                if (pkgName.equals(item.packageName)) {
11700                    iter.remove();
11701                }
11702            }
11703
11704            // Add the package's KeySets to the global KeySetManagerService
11705            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11706            ksms.addScannedPackageLPw(pkg);
11707
11708            int N = pkg.providers.size();
11709            StringBuilder r = null;
11710            int i;
11711            for (i=0; i<N; i++) {
11712                PackageParser.Provider p = pkg.providers.get(i);
11713                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11714                        p.info.processName);
11715                mProviders.addProvider(p);
11716                p.syncable = p.info.isSyncable;
11717                if (p.info.authority != null) {
11718                    String names[] = p.info.authority.split(";");
11719                    p.info.authority = null;
11720                    for (int j = 0; j < names.length; j++) {
11721                        if (j == 1 && p.syncable) {
11722                            // We only want the first authority for a provider to possibly be
11723                            // syncable, so if we already added this provider using a different
11724                            // authority clear the syncable flag. We copy the provider before
11725                            // changing it because the mProviders object contains a reference
11726                            // to a provider that we don't want to change.
11727                            // Only do this for the second authority since the resulting provider
11728                            // object can be the same for all future authorities for this provider.
11729                            p = new PackageParser.Provider(p);
11730                            p.syncable = false;
11731                        }
11732                        if (!mProvidersByAuthority.containsKey(names[j])) {
11733                            mProvidersByAuthority.put(names[j], p);
11734                            if (p.info.authority == null) {
11735                                p.info.authority = names[j];
11736                            } else {
11737                                p.info.authority = p.info.authority + ";" + names[j];
11738                            }
11739                            if (DEBUG_PACKAGE_SCANNING) {
11740                                if (chatty)
11741                                    Log.d(TAG, "Registered content provider: " + names[j]
11742                                            + ", className = " + p.info.name + ", isSyncable = "
11743                                            + p.info.isSyncable);
11744                            }
11745                        } else {
11746                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11747                            Slog.w(TAG, "Skipping provider name " + names[j] +
11748                                    " (in package " + pkg.applicationInfo.packageName +
11749                                    "): name already used by "
11750                                    + ((other != null && other.getComponentName() != null)
11751                                            ? other.getComponentName().getPackageName() : "?"));
11752                        }
11753                    }
11754                }
11755                if (chatty) {
11756                    if (r == null) {
11757                        r = new StringBuilder(256);
11758                    } else {
11759                        r.append(' ');
11760                    }
11761                    r.append(p.info.name);
11762                }
11763            }
11764            if (r != null) {
11765                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11766            }
11767
11768            N = pkg.services.size();
11769            r = null;
11770            for (i=0; i<N; i++) {
11771                PackageParser.Service s = pkg.services.get(i);
11772                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11773                        s.info.processName);
11774                mServices.addService(s);
11775                if (chatty) {
11776                    if (r == null) {
11777                        r = new StringBuilder(256);
11778                    } else {
11779                        r.append(' ');
11780                    }
11781                    r.append(s.info.name);
11782                }
11783            }
11784            if (r != null) {
11785                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11786            }
11787
11788            N = pkg.receivers.size();
11789            r = null;
11790            for (i=0; i<N; i++) {
11791                PackageParser.Activity a = pkg.receivers.get(i);
11792                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11793                        a.info.processName);
11794                mReceivers.addActivity(a, "receiver");
11795                if (chatty) {
11796                    if (r == null) {
11797                        r = new StringBuilder(256);
11798                    } else {
11799                        r.append(' ');
11800                    }
11801                    r.append(a.info.name);
11802                }
11803            }
11804            if (r != null) {
11805                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11806            }
11807
11808            N = pkg.activities.size();
11809            r = null;
11810            for (i=0; i<N; i++) {
11811                PackageParser.Activity a = pkg.activities.get(i);
11812                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11813                        a.info.processName);
11814                mActivities.addActivity(a, "activity");
11815                if (chatty) {
11816                    if (r == null) {
11817                        r = new StringBuilder(256);
11818                    } else {
11819                        r.append(' ');
11820                    }
11821                    r.append(a.info.name);
11822                }
11823            }
11824            if (r != null) {
11825                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11826            }
11827
11828            N = pkg.permissionGroups.size();
11829            r = null;
11830            for (i=0; i<N; i++) {
11831                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11832                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11833                final String curPackageName = cur == null ? null : cur.info.packageName;
11834                // Dont allow ephemeral apps to define new permission groups.
11835                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11836                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11837                            + pg.info.packageName
11838                            + " ignored: instant apps cannot define new permission groups.");
11839                    continue;
11840                }
11841                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11842                if (cur == null || isPackageUpdate) {
11843                    mPermissionGroups.put(pg.info.name, pg);
11844                    if (chatty) {
11845                        if (r == null) {
11846                            r = new StringBuilder(256);
11847                        } else {
11848                            r.append(' ');
11849                        }
11850                        if (isPackageUpdate) {
11851                            r.append("UPD:");
11852                        }
11853                        r.append(pg.info.name);
11854                    }
11855                } else {
11856                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11857                            + pg.info.packageName + " ignored: original from "
11858                            + cur.info.packageName);
11859                    if (chatty) {
11860                        if (r == null) {
11861                            r = new StringBuilder(256);
11862                        } else {
11863                            r.append(' ');
11864                        }
11865                        r.append("DUP:");
11866                        r.append(pg.info.name);
11867                    }
11868                }
11869            }
11870            if (r != null) {
11871                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11872            }
11873
11874            N = pkg.permissions.size();
11875            r = null;
11876            for (i=0; i<N; i++) {
11877                PackageParser.Permission p = pkg.permissions.get(i);
11878
11879                // Dont allow ephemeral apps to define new permissions.
11880                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11881                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11882                            + p.info.packageName
11883                            + " ignored: instant apps cannot define new permissions.");
11884                    continue;
11885                }
11886
11887                // Assume by default that we did not install this permission into the system.
11888                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11889
11890                // Now that permission groups have a special meaning, we ignore permission
11891                // groups for legacy apps to prevent unexpected behavior. In particular,
11892                // permissions for one app being granted to someone just because they happen
11893                // to be in a group defined by another app (before this had no implications).
11894                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11895                    p.group = mPermissionGroups.get(p.info.group);
11896                    // Warn for a permission in an unknown group.
11897                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11898                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11899                                + p.info.packageName + " in an unknown group " + p.info.group);
11900                    }
11901                }
11902
11903                ArrayMap<String, BasePermission> permissionMap =
11904                        p.tree ? mSettings.mPermissionTrees
11905                                : mSettings.mPermissions;
11906                BasePermission bp = permissionMap.get(p.info.name);
11907
11908                // Allow system apps to redefine non-system permissions
11909                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11910                    final boolean currentOwnerIsSystem = (bp.perm != null
11911                            && isSystemApp(bp.perm.owner));
11912                    if (isSystemApp(p.owner)) {
11913                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11914                            // It's a built-in permission and no owner, take ownership now
11915                            bp.packageSetting = pkgSetting;
11916                            bp.perm = p;
11917                            bp.uid = pkg.applicationInfo.uid;
11918                            bp.sourcePackage = p.info.packageName;
11919                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11920                        } else if (!currentOwnerIsSystem) {
11921                            String msg = "New decl " + p.owner + " of permission  "
11922                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11923                            reportSettingsProblem(Log.WARN, msg);
11924                            bp = null;
11925                        }
11926                    }
11927                }
11928
11929                if (bp == null) {
11930                    bp = new BasePermission(p.info.name, p.info.packageName,
11931                            BasePermission.TYPE_NORMAL);
11932                    permissionMap.put(p.info.name, bp);
11933                }
11934
11935                if (bp.perm == null) {
11936                    if (bp.sourcePackage == null
11937                            || bp.sourcePackage.equals(p.info.packageName)) {
11938                        BasePermission tree = findPermissionTreeLP(p.info.name);
11939                        if (tree == null
11940                                || tree.sourcePackage.equals(p.info.packageName)) {
11941                            bp.packageSetting = pkgSetting;
11942                            bp.perm = p;
11943                            bp.uid = pkg.applicationInfo.uid;
11944                            bp.sourcePackage = p.info.packageName;
11945                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11946                            if (chatty) {
11947                                if (r == null) {
11948                                    r = new StringBuilder(256);
11949                                } else {
11950                                    r.append(' ');
11951                                }
11952                                r.append(p.info.name);
11953                            }
11954                        } else {
11955                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11956                                    + p.info.packageName + " ignored: base tree "
11957                                    + tree.name + " is from package "
11958                                    + tree.sourcePackage);
11959                        }
11960                    } else {
11961                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11962                                + p.info.packageName + " ignored: original from "
11963                                + bp.sourcePackage);
11964                    }
11965                } else if (chatty) {
11966                    if (r == null) {
11967                        r = new StringBuilder(256);
11968                    } else {
11969                        r.append(' ');
11970                    }
11971                    r.append("DUP:");
11972                    r.append(p.info.name);
11973                }
11974                if (bp.perm == p) {
11975                    bp.protectionLevel = p.info.protectionLevel;
11976                }
11977            }
11978
11979            if (r != null) {
11980                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11981            }
11982
11983            N = pkg.instrumentation.size();
11984            r = null;
11985            for (i=0; i<N; i++) {
11986                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11987                a.info.packageName = pkg.applicationInfo.packageName;
11988                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11989                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11990                a.info.splitNames = pkg.splitNames;
11991                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11992                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11993                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11994                a.info.dataDir = pkg.applicationInfo.dataDir;
11995                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11996                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11997                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11998                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11999                mInstrumentation.put(a.getComponentName(), a);
12000                if (chatty) {
12001                    if (r == null) {
12002                        r = new StringBuilder(256);
12003                    } else {
12004                        r.append(' ');
12005                    }
12006                    r.append(a.info.name);
12007                }
12008            }
12009            if (r != null) {
12010                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
12011            }
12012
12013            if (pkg.protectedBroadcasts != null) {
12014                N = pkg.protectedBroadcasts.size();
12015                synchronized (mProtectedBroadcasts) {
12016                    for (i = 0; i < N; i++) {
12017                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
12018                    }
12019                }
12020            }
12021        }
12022
12023        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12024    }
12025
12026    /**
12027     * Derive the ABI of a non-system package located at {@code scanFile}. This information
12028     * is derived purely on the basis of the contents of {@code scanFile} and
12029     * {@code cpuAbiOverride}.
12030     *
12031     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
12032     */
12033    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
12034                                 String cpuAbiOverride, boolean extractLibs,
12035                                 File appLib32InstallDir)
12036            throws PackageManagerException {
12037        // Give ourselves some initial paths; we'll come back for another
12038        // pass once we've determined ABI below.
12039        setNativeLibraryPaths(pkg, appLib32InstallDir);
12040
12041        // We would never need to extract libs for forward-locked and external packages,
12042        // since the container service will do it for us. We shouldn't attempt to
12043        // extract libs from system app when it was not updated.
12044        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
12045                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
12046            extractLibs = false;
12047        }
12048
12049        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
12050        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
12051
12052        NativeLibraryHelper.Handle handle = null;
12053        try {
12054            handle = NativeLibraryHelper.Handle.create(pkg);
12055            // TODO(multiArch): This can be null for apps that didn't go through the
12056            // usual installation process. We can calculate it again, like we
12057            // do during install time.
12058            //
12059            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
12060            // unnecessary.
12061            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
12062
12063            // Null out the abis so that they can be recalculated.
12064            pkg.applicationInfo.primaryCpuAbi = null;
12065            pkg.applicationInfo.secondaryCpuAbi = null;
12066            if (isMultiArch(pkg.applicationInfo)) {
12067                // Warn if we've set an abiOverride for multi-lib packages..
12068                // By definition, we need to copy both 32 and 64 bit libraries for
12069                // such packages.
12070                if (pkg.cpuAbiOverride != null
12071                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
12072                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
12073                }
12074
12075                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
12076                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
12077                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
12078                    if (extractLibs) {
12079                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12080                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12081                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12082                                useIsaSpecificSubdirs);
12083                    } else {
12084                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12085                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12086                    }
12087                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12088                }
12089
12090                // Shared library native code should be in the APK zip aligned
12091                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12092                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12093                            "Shared library native lib extraction not supported");
12094                }
12095
12096                maybeThrowExceptionForMultiArchCopy(
12097                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12098
12099                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12100                    if (extractLibs) {
12101                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12102                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12103                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12104                                useIsaSpecificSubdirs);
12105                    } else {
12106                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12107                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12108                    }
12109                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12110                }
12111
12112                maybeThrowExceptionForMultiArchCopy(
12113                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12114
12115                if (abi64 >= 0) {
12116                    // Shared library native libs should be in the APK zip aligned
12117                    if (extractLibs && pkg.isLibrary()) {
12118                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12119                                "Shared library native lib extraction not supported");
12120                    }
12121                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12122                }
12123
12124                if (abi32 >= 0) {
12125                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12126                    if (abi64 >= 0) {
12127                        if (pkg.use32bitAbi) {
12128                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12129                            pkg.applicationInfo.primaryCpuAbi = abi;
12130                        } else {
12131                            pkg.applicationInfo.secondaryCpuAbi = abi;
12132                        }
12133                    } else {
12134                        pkg.applicationInfo.primaryCpuAbi = abi;
12135                    }
12136                }
12137            } else {
12138                String[] abiList = (cpuAbiOverride != null) ?
12139                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12140
12141                // Enable gross and lame hacks for apps that are built with old
12142                // SDK tools. We must scan their APKs for renderscript bitcode and
12143                // not launch them if it's present. Don't bother checking on devices
12144                // that don't have 64 bit support.
12145                boolean needsRenderScriptOverride = false;
12146                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12147                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12148                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12149                    needsRenderScriptOverride = true;
12150                }
12151
12152                final int copyRet;
12153                if (extractLibs) {
12154                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12155                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12156                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12157                } else {
12158                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12159                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12160                }
12161                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12162
12163                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12164                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12165                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12166                }
12167
12168                if (copyRet >= 0) {
12169                    // Shared libraries that have native libs must be multi-architecture
12170                    if (pkg.isLibrary()) {
12171                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12172                                "Shared library with native libs must be multiarch");
12173                    }
12174                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12175                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12176                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12177                } else if (needsRenderScriptOverride) {
12178                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12179                }
12180            }
12181        } catch (IOException ioe) {
12182            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12183        } finally {
12184            IoUtils.closeQuietly(handle);
12185        }
12186
12187        // Now that we've calculated the ABIs and determined if it's an internal app,
12188        // we will go ahead and populate the nativeLibraryPath.
12189        setNativeLibraryPaths(pkg, appLib32InstallDir);
12190    }
12191
12192    /**
12193     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12194     * i.e, so that all packages can be run inside a single process if required.
12195     *
12196     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12197     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12198     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12199     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12200     * updating a package that belongs to a shared user.
12201     *
12202     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12203     * adds unnecessary complexity.
12204     */
12205    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12206            PackageParser.Package scannedPackage) {
12207        String requiredInstructionSet = null;
12208        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12209            requiredInstructionSet = VMRuntime.getInstructionSet(
12210                     scannedPackage.applicationInfo.primaryCpuAbi);
12211        }
12212
12213        PackageSetting requirer = null;
12214        for (PackageSetting ps : packagesForUser) {
12215            // If packagesForUser contains scannedPackage, we skip it. This will happen
12216            // when scannedPackage is an update of an existing package. Without this check,
12217            // we will never be able to change the ABI of any package belonging to a shared
12218            // user, even if it's compatible with other packages.
12219            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12220                if (ps.primaryCpuAbiString == null) {
12221                    continue;
12222                }
12223
12224                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12225                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12226                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12227                    // this but there's not much we can do.
12228                    String errorMessage = "Instruction set mismatch, "
12229                            + ((requirer == null) ? "[caller]" : requirer)
12230                            + " requires " + requiredInstructionSet + " whereas " + ps
12231                            + " requires " + instructionSet;
12232                    Slog.w(TAG, errorMessage);
12233                }
12234
12235                if (requiredInstructionSet == null) {
12236                    requiredInstructionSet = instructionSet;
12237                    requirer = ps;
12238                }
12239            }
12240        }
12241
12242        if (requiredInstructionSet != null) {
12243            String adjustedAbi;
12244            if (requirer != null) {
12245                // requirer != null implies that either scannedPackage was null or that scannedPackage
12246                // did not require an ABI, in which case we have to adjust scannedPackage to match
12247                // the ABI of the set (which is the same as requirer's ABI)
12248                adjustedAbi = requirer.primaryCpuAbiString;
12249                if (scannedPackage != null) {
12250                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12251                }
12252            } else {
12253                // requirer == null implies that we're updating all ABIs in the set to
12254                // match scannedPackage.
12255                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12256            }
12257
12258            for (PackageSetting ps : packagesForUser) {
12259                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12260                    if (ps.primaryCpuAbiString != null) {
12261                        continue;
12262                    }
12263
12264                    ps.primaryCpuAbiString = adjustedAbi;
12265                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12266                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12267                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12268                        if (DEBUG_ABI_SELECTION) {
12269                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12270                                    + " (requirer="
12271                                    + (requirer != null ? requirer.pkg : "null")
12272                                    + ", scannedPackage="
12273                                    + (scannedPackage != null ? scannedPackage : "null")
12274                                    + ")");
12275                        }
12276                        try {
12277                            mInstaller.rmdex(ps.codePathString,
12278                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12279                        } catch (InstallerException ignored) {
12280                        }
12281                    }
12282                }
12283            }
12284        }
12285    }
12286
12287    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12288        synchronized (mPackages) {
12289            mResolverReplaced = true;
12290            // Set up information for custom user intent resolution activity.
12291            mResolveActivity.applicationInfo = pkg.applicationInfo;
12292            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12293            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12294            mResolveActivity.processName = pkg.applicationInfo.packageName;
12295            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12296            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12297                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12298            mResolveActivity.theme = 0;
12299            mResolveActivity.exported = true;
12300            mResolveActivity.enabled = true;
12301            mResolveInfo.activityInfo = mResolveActivity;
12302            mResolveInfo.priority = 0;
12303            mResolveInfo.preferredOrder = 0;
12304            mResolveInfo.match = 0;
12305            mResolveComponentName = mCustomResolverComponentName;
12306            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12307                    mResolveComponentName);
12308        }
12309    }
12310
12311    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12312        if (installerActivity == null) {
12313            if (DEBUG_EPHEMERAL) {
12314                Slog.d(TAG, "Clear ephemeral installer activity");
12315            }
12316            mInstantAppInstallerActivity = null;
12317            return;
12318        }
12319
12320        if (DEBUG_EPHEMERAL) {
12321            Slog.d(TAG, "Set ephemeral installer activity: "
12322                    + installerActivity.getComponentName());
12323        }
12324        // Set up information for ephemeral installer activity
12325        mInstantAppInstallerActivity = installerActivity;
12326        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12327                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12328        mInstantAppInstallerActivity.exported = true;
12329        mInstantAppInstallerActivity.enabled = true;
12330        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12331        mInstantAppInstallerInfo.priority = 0;
12332        mInstantAppInstallerInfo.preferredOrder = 1;
12333        mInstantAppInstallerInfo.isDefault = true;
12334        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12335                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12336    }
12337
12338    private static String calculateBundledApkRoot(final String codePathString) {
12339        final File codePath = new File(codePathString);
12340        final File codeRoot;
12341        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12342            codeRoot = Environment.getRootDirectory();
12343        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12344            codeRoot = Environment.getOemDirectory();
12345        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12346            codeRoot = Environment.getVendorDirectory();
12347        } else {
12348            // Unrecognized code path; take its top real segment as the apk root:
12349            // e.g. /something/app/blah.apk => /something
12350            try {
12351                File f = codePath.getCanonicalFile();
12352                File parent = f.getParentFile();    // non-null because codePath is a file
12353                File tmp;
12354                while ((tmp = parent.getParentFile()) != null) {
12355                    f = parent;
12356                    parent = tmp;
12357                }
12358                codeRoot = f;
12359                Slog.w(TAG, "Unrecognized code path "
12360                        + codePath + " - using " + codeRoot);
12361            } catch (IOException e) {
12362                // Can't canonicalize the code path -- shenanigans?
12363                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12364                return Environment.getRootDirectory().getPath();
12365            }
12366        }
12367        return codeRoot.getPath();
12368    }
12369
12370    /**
12371     * Derive and set the location of native libraries for the given package,
12372     * which varies depending on where and how the package was installed.
12373     */
12374    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12375        final ApplicationInfo info = pkg.applicationInfo;
12376        final String codePath = pkg.codePath;
12377        final File codeFile = new File(codePath);
12378        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12379        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12380
12381        info.nativeLibraryRootDir = null;
12382        info.nativeLibraryRootRequiresIsa = false;
12383        info.nativeLibraryDir = null;
12384        info.secondaryNativeLibraryDir = null;
12385
12386        if (isApkFile(codeFile)) {
12387            // Monolithic install
12388            if (bundledApp) {
12389                // If "/system/lib64/apkname" exists, assume that is the per-package
12390                // native library directory to use; otherwise use "/system/lib/apkname".
12391                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12392                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12393                        getPrimaryInstructionSet(info));
12394
12395                // This is a bundled system app so choose the path based on the ABI.
12396                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12397                // is just the default path.
12398                final String apkName = deriveCodePathName(codePath);
12399                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12400                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12401                        apkName).getAbsolutePath();
12402
12403                if (info.secondaryCpuAbi != null) {
12404                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12405                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12406                            secondaryLibDir, apkName).getAbsolutePath();
12407                }
12408            } else if (asecApp) {
12409                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12410                        .getAbsolutePath();
12411            } else {
12412                final String apkName = deriveCodePathName(codePath);
12413                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12414                        .getAbsolutePath();
12415            }
12416
12417            info.nativeLibraryRootRequiresIsa = false;
12418            info.nativeLibraryDir = info.nativeLibraryRootDir;
12419        } else {
12420            // Cluster install
12421            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12422            info.nativeLibraryRootRequiresIsa = true;
12423
12424            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12425                    getPrimaryInstructionSet(info)).getAbsolutePath();
12426
12427            if (info.secondaryCpuAbi != null) {
12428                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12429                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12430            }
12431        }
12432    }
12433
12434    /**
12435     * Calculate the abis and roots for a bundled app. These can uniquely
12436     * be determined from the contents of the system partition, i.e whether
12437     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12438     * of this information, and instead assume that the system was built
12439     * sensibly.
12440     */
12441    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12442                                           PackageSetting pkgSetting) {
12443        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12444
12445        // If "/system/lib64/apkname" exists, assume that is the per-package
12446        // native library directory to use; otherwise use "/system/lib/apkname".
12447        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12448        setBundledAppAbi(pkg, apkRoot, apkName);
12449        // pkgSetting might be null during rescan following uninstall of updates
12450        // to a bundled app, so accommodate that possibility.  The settings in
12451        // that case will be established later from the parsed package.
12452        //
12453        // If the settings aren't null, sync them up with what we've just derived.
12454        // note that apkRoot isn't stored in the package settings.
12455        if (pkgSetting != null) {
12456            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12457            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12458        }
12459    }
12460
12461    /**
12462     * Deduces the ABI of a bundled app and sets the relevant fields on the
12463     * parsed pkg object.
12464     *
12465     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12466     *        under which system libraries are installed.
12467     * @param apkName the name of the installed package.
12468     */
12469    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12470        final File codeFile = new File(pkg.codePath);
12471
12472        final boolean has64BitLibs;
12473        final boolean has32BitLibs;
12474        if (isApkFile(codeFile)) {
12475            // Monolithic install
12476            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12477            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12478        } else {
12479            // Cluster install
12480            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12481            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12482                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12483                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12484                has64BitLibs = (new File(rootDir, isa)).exists();
12485            } else {
12486                has64BitLibs = false;
12487            }
12488            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12489                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12490                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12491                has32BitLibs = (new File(rootDir, isa)).exists();
12492            } else {
12493                has32BitLibs = false;
12494            }
12495        }
12496
12497        if (has64BitLibs && !has32BitLibs) {
12498            // The package has 64 bit libs, but not 32 bit libs. Its primary
12499            // ABI should be 64 bit. We can safely assume here that the bundled
12500            // native libraries correspond to the most preferred ABI in the list.
12501
12502            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12503            pkg.applicationInfo.secondaryCpuAbi = null;
12504        } else if (has32BitLibs && !has64BitLibs) {
12505            // The package has 32 bit libs but not 64 bit libs. Its primary
12506            // ABI should be 32 bit.
12507
12508            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12509            pkg.applicationInfo.secondaryCpuAbi = null;
12510        } else if (has32BitLibs && has64BitLibs) {
12511            // The application has both 64 and 32 bit bundled libraries. We check
12512            // here that the app declares multiArch support, and warn if it doesn't.
12513            //
12514            // We will be lenient here and record both ABIs. The primary will be the
12515            // ABI that's higher on the list, i.e, a device that's configured to prefer
12516            // 64 bit apps will see a 64 bit primary ABI,
12517
12518            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12519                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12520            }
12521
12522            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12523                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12524                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12525            } else {
12526                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12527                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12528            }
12529        } else {
12530            pkg.applicationInfo.primaryCpuAbi = null;
12531            pkg.applicationInfo.secondaryCpuAbi = null;
12532        }
12533    }
12534
12535    private void killApplication(String pkgName, int appId, String reason) {
12536        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12537    }
12538
12539    private void killApplication(String pkgName, int appId, int userId, String reason) {
12540        // Request the ActivityManager to kill the process(only for existing packages)
12541        // so that we do not end up in a confused state while the user is still using the older
12542        // version of the application while the new one gets installed.
12543        final long token = Binder.clearCallingIdentity();
12544        try {
12545            IActivityManager am = ActivityManager.getService();
12546            if (am != null) {
12547                try {
12548                    am.killApplication(pkgName, appId, userId, reason);
12549                } catch (RemoteException e) {
12550                }
12551            }
12552        } finally {
12553            Binder.restoreCallingIdentity(token);
12554        }
12555    }
12556
12557    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12558        // Remove the parent package setting
12559        PackageSetting ps = (PackageSetting) pkg.mExtras;
12560        if (ps != null) {
12561            removePackageLI(ps, chatty);
12562        }
12563        // Remove the child package setting
12564        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12565        for (int i = 0; i < childCount; i++) {
12566            PackageParser.Package childPkg = pkg.childPackages.get(i);
12567            ps = (PackageSetting) childPkg.mExtras;
12568            if (ps != null) {
12569                removePackageLI(ps, chatty);
12570            }
12571        }
12572    }
12573
12574    void removePackageLI(PackageSetting ps, boolean chatty) {
12575        if (DEBUG_INSTALL) {
12576            if (chatty)
12577                Log.d(TAG, "Removing package " + ps.name);
12578        }
12579
12580        // writer
12581        synchronized (mPackages) {
12582            mPackages.remove(ps.name);
12583            final PackageParser.Package pkg = ps.pkg;
12584            if (pkg != null) {
12585                cleanPackageDataStructuresLILPw(pkg, chatty);
12586            }
12587        }
12588    }
12589
12590    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12591        if (DEBUG_INSTALL) {
12592            if (chatty)
12593                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12594        }
12595
12596        // writer
12597        synchronized (mPackages) {
12598            // Remove the parent package
12599            mPackages.remove(pkg.applicationInfo.packageName);
12600            cleanPackageDataStructuresLILPw(pkg, chatty);
12601
12602            // Remove the child packages
12603            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12604            for (int i = 0; i < childCount; i++) {
12605                PackageParser.Package childPkg = pkg.childPackages.get(i);
12606                mPackages.remove(childPkg.applicationInfo.packageName);
12607                cleanPackageDataStructuresLILPw(childPkg, chatty);
12608            }
12609        }
12610    }
12611
12612    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12613        int N = pkg.providers.size();
12614        StringBuilder r = null;
12615        int i;
12616        for (i=0; i<N; i++) {
12617            PackageParser.Provider p = pkg.providers.get(i);
12618            mProviders.removeProvider(p);
12619            if (p.info.authority == null) {
12620
12621                /* There was another ContentProvider with this authority when
12622                 * this app was installed so this authority is null,
12623                 * Ignore it as we don't have to unregister the provider.
12624                 */
12625                continue;
12626            }
12627            String names[] = p.info.authority.split(";");
12628            for (int j = 0; j < names.length; j++) {
12629                if (mProvidersByAuthority.get(names[j]) == p) {
12630                    mProvidersByAuthority.remove(names[j]);
12631                    if (DEBUG_REMOVE) {
12632                        if (chatty)
12633                            Log.d(TAG, "Unregistered content provider: " + names[j]
12634                                    + ", className = " + p.info.name + ", isSyncable = "
12635                                    + p.info.isSyncable);
12636                    }
12637                }
12638            }
12639            if (DEBUG_REMOVE && chatty) {
12640                if (r == null) {
12641                    r = new StringBuilder(256);
12642                } else {
12643                    r.append(' ');
12644                }
12645                r.append(p.info.name);
12646            }
12647        }
12648        if (r != null) {
12649            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12650        }
12651
12652        N = pkg.services.size();
12653        r = null;
12654        for (i=0; i<N; i++) {
12655            PackageParser.Service s = pkg.services.get(i);
12656            mServices.removeService(s);
12657            if (chatty) {
12658                if (r == null) {
12659                    r = new StringBuilder(256);
12660                } else {
12661                    r.append(' ');
12662                }
12663                r.append(s.info.name);
12664            }
12665        }
12666        if (r != null) {
12667            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12668        }
12669
12670        N = pkg.receivers.size();
12671        r = null;
12672        for (i=0; i<N; i++) {
12673            PackageParser.Activity a = pkg.receivers.get(i);
12674            mReceivers.removeActivity(a, "receiver");
12675            if (DEBUG_REMOVE && chatty) {
12676                if (r == null) {
12677                    r = new StringBuilder(256);
12678                } else {
12679                    r.append(' ');
12680                }
12681                r.append(a.info.name);
12682            }
12683        }
12684        if (r != null) {
12685            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12686        }
12687
12688        N = pkg.activities.size();
12689        r = null;
12690        for (i=0; i<N; i++) {
12691            PackageParser.Activity a = pkg.activities.get(i);
12692            mActivities.removeActivity(a, "activity");
12693            if (DEBUG_REMOVE && chatty) {
12694                if (r == null) {
12695                    r = new StringBuilder(256);
12696                } else {
12697                    r.append(' ');
12698                }
12699                r.append(a.info.name);
12700            }
12701        }
12702        if (r != null) {
12703            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12704        }
12705
12706        N = pkg.permissions.size();
12707        r = null;
12708        for (i=0; i<N; i++) {
12709            PackageParser.Permission p = pkg.permissions.get(i);
12710            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12711            if (bp == null) {
12712                bp = mSettings.mPermissionTrees.get(p.info.name);
12713            }
12714            if (bp != null && bp.perm == p) {
12715                bp.perm = null;
12716                if (DEBUG_REMOVE && chatty) {
12717                    if (r == null) {
12718                        r = new StringBuilder(256);
12719                    } else {
12720                        r.append(' ');
12721                    }
12722                    r.append(p.info.name);
12723                }
12724            }
12725            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12726                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12727                if (appOpPkgs != null) {
12728                    appOpPkgs.remove(pkg.packageName);
12729                }
12730            }
12731        }
12732        if (r != null) {
12733            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12734        }
12735
12736        N = pkg.requestedPermissions.size();
12737        r = null;
12738        for (i=0; i<N; i++) {
12739            String perm = pkg.requestedPermissions.get(i);
12740            BasePermission bp = mSettings.mPermissions.get(perm);
12741            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12742                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12743                if (appOpPkgs != null) {
12744                    appOpPkgs.remove(pkg.packageName);
12745                    if (appOpPkgs.isEmpty()) {
12746                        mAppOpPermissionPackages.remove(perm);
12747                    }
12748                }
12749            }
12750        }
12751        if (r != null) {
12752            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12753        }
12754
12755        N = pkg.instrumentation.size();
12756        r = null;
12757        for (i=0; i<N; i++) {
12758            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12759            mInstrumentation.remove(a.getComponentName());
12760            if (DEBUG_REMOVE && chatty) {
12761                if (r == null) {
12762                    r = new StringBuilder(256);
12763                } else {
12764                    r.append(' ');
12765                }
12766                r.append(a.info.name);
12767            }
12768        }
12769        if (r != null) {
12770            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12771        }
12772
12773        r = null;
12774        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12775            // Only system apps can hold shared libraries.
12776            if (pkg.libraryNames != null) {
12777                for (i = 0; i < pkg.libraryNames.size(); i++) {
12778                    String name = pkg.libraryNames.get(i);
12779                    if (removeSharedLibraryLPw(name, 0)) {
12780                        if (DEBUG_REMOVE && chatty) {
12781                            if (r == null) {
12782                                r = new StringBuilder(256);
12783                            } else {
12784                                r.append(' ');
12785                            }
12786                            r.append(name);
12787                        }
12788                    }
12789                }
12790            }
12791        }
12792
12793        r = null;
12794
12795        // Any package can hold static shared libraries.
12796        if (pkg.staticSharedLibName != null) {
12797            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12798                if (DEBUG_REMOVE && chatty) {
12799                    if (r == null) {
12800                        r = new StringBuilder(256);
12801                    } else {
12802                        r.append(' ');
12803                    }
12804                    r.append(pkg.staticSharedLibName);
12805                }
12806            }
12807        }
12808
12809        if (r != null) {
12810            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12811        }
12812    }
12813
12814    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12815        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12816            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12817                return true;
12818            }
12819        }
12820        return false;
12821    }
12822
12823    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12824    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12825    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12826
12827    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12828        // Update the parent permissions
12829        updatePermissionsLPw(pkg.packageName, pkg, flags);
12830        // Update the child permissions
12831        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12832        for (int i = 0; i < childCount; i++) {
12833            PackageParser.Package childPkg = pkg.childPackages.get(i);
12834            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12835        }
12836    }
12837
12838    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12839            int flags) {
12840        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12841        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12842    }
12843
12844    private void updatePermissionsLPw(String changingPkg,
12845            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12846        // Make sure there are no dangling permission trees.
12847        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12848        while (it.hasNext()) {
12849            final BasePermission bp = it.next();
12850            if (bp.packageSetting == null) {
12851                // We may not yet have parsed the package, so just see if
12852                // we still know about its settings.
12853                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12854            }
12855            if (bp.packageSetting == null) {
12856                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12857                        + " from package " + bp.sourcePackage);
12858                it.remove();
12859            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12860                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12861                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12862                            + " from package " + bp.sourcePackage);
12863                    flags |= UPDATE_PERMISSIONS_ALL;
12864                    it.remove();
12865                }
12866            }
12867        }
12868
12869        // Make sure all dynamic permissions have been assigned to a package,
12870        // and make sure there are no dangling permissions.
12871        it = mSettings.mPermissions.values().iterator();
12872        while (it.hasNext()) {
12873            final BasePermission bp = it.next();
12874            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12875                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12876                        + bp.name + " pkg=" + bp.sourcePackage
12877                        + " info=" + bp.pendingInfo);
12878                if (bp.packageSetting == null && bp.pendingInfo != null) {
12879                    final BasePermission tree = findPermissionTreeLP(bp.name);
12880                    if (tree != null && tree.perm != null) {
12881                        bp.packageSetting = tree.packageSetting;
12882                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12883                                new PermissionInfo(bp.pendingInfo));
12884                        bp.perm.info.packageName = tree.perm.info.packageName;
12885                        bp.perm.info.name = bp.name;
12886                        bp.uid = tree.uid;
12887                    }
12888                }
12889            }
12890            if (bp.packageSetting == null) {
12891                // We may not yet have parsed the package, so just see if
12892                // we still know about its settings.
12893                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12894            }
12895            if (bp.packageSetting == null) {
12896                Slog.w(TAG, "Removing dangling permission: " + bp.name
12897                        + " from package " + bp.sourcePackage);
12898                it.remove();
12899            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12900                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12901                    Slog.i(TAG, "Removing old permission: " + bp.name
12902                            + " from package " + bp.sourcePackage);
12903                    flags |= UPDATE_PERMISSIONS_ALL;
12904                    it.remove();
12905                }
12906            }
12907        }
12908
12909        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12910        // Now update the permissions for all packages, in particular
12911        // replace the granted permissions of the system packages.
12912        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12913            for (PackageParser.Package pkg : mPackages.values()) {
12914                if (pkg != pkgInfo) {
12915                    // Only replace for packages on requested volume
12916                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12917                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12918                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12919                    grantPermissionsLPw(pkg, replace, changingPkg);
12920                }
12921            }
12922        }
12923
12924        if (pkgInfo != null) {
12925            // Only replace for packages on requested volume
12926            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12927            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12928                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12929            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12930        }
12931        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12932    }
12933
12934    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12935            String packageOfInterest) {
12936        // IMPORTANT: There are two types of permissions: install and runtime.
12937        // Install time permissions are granted when the app is installed to
12938        // all device users and users added in the future. Runtime permissions
12939        // are granted at runtime explicitly to specific users. Normal and signature
12940        // protected permissions are install time permissions. Dangerous permissions
12941        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12942        // otherwise they are runtime permissions. This function does not manage
12943        // runtime permissions except for the case an app targeting Lollipop MR1
12944        // being upgraded to target a newer SDK, in which case dangerous permissions
12945        // are transformed from install time to runtime ones.
12946
12947        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12948        if (ps == null) {
12949            return;
12950        }
12951
12952        PermissionsState permissionsState = ps.getPermissionsState();
12953        PermissionsState origPermissions = permissionsState;
12954
12955        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12956
12957        boolean runtimePermissionsRevoked = false;
12958        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12959
12960        boolean changedInstallPermission = false;
12961
12962        if (replace) {
12963            ps.installPermissionsFixed = false;
12964            if (!ps.isSharedUser()) {
12965                origPermissions = new PermissionsState(permissionsState);
12966                permissionsState.reset();
12967            } else {
12968                // We need to know only about runtime permission changes since the
12969                // calling code always writes the install permissions state but
12970                // the runtime ones are written only if changed. The only cases of
12971                // changed runtime permissions here are promotion of an install to
12972                // runtime and revocation of a runtime from a shared user.
12973                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12974                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12975                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12976                    runtimePermissionsRevoked = true;
12977                }
12978            }
12979        }
12980
12981        permissionsState.setGlobalGids(mGlobalGids);
12982
12983        final int N = pkg.requestedPermissions.size();
12984        for (int i=0; i<N; i++) {
12985            final String name = pkg.requestedPermissions.get(i);
12986            final BasePermission bp = mSettings.mPermissions.get(name);
12987            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12988                    >= Build.VERSION_CODES.M;
12989
12990            if (DEBUG_INSTALL) {
12991                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12992            }
12993
12994            if (bp == null || bp.packageSetting == null) {
12995                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12996                    if (DEBUG_PERMISSIONS) {
12997                        Slog.i(TAG, "Unknown permission " + name
12998                                + " in package " + pkg.packageName);
12999                    }
13000                }
13001                continue;
13002            }
13003
13004
13005            // Limit ephemeral apps to ephemeral allowed permissions.
13006            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
13007                if (DEBUG_PERMISSIONS) {
13008                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
13009                            + pkg.packageName);
13010                }
13011                continue;
13012            }
13013
13014            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
13015                if (DEBUG_PERMISSIONS) {
13016                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
13017                            + pkg.packageName);
13018                }
13019                continue;
13020            }
13021
13022            final String perm = bp.name;
13023            boolean allowedSig = false;
13024            int grant = GRANT_DENIED;
13025
13026            // Keep track of app op permissions.
13027            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
13028                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
13029                if (pkgs == null) {
13030                    pkgs = new ArraySet<>();
13031                    mAppOpPermissionPackages.put(bp.name, pkgs);
13032                }
13033                pkgs.add(pkg.packageName);
13034            }
13035
13036            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
13037            switch (level) {
13038                case PermissionInfo.PROTECTION_NORMAL: {
13039                    // For all apps normal permissions are install time ones.
13040                    grant = GRANT_INSTALL;
13041                } break;
13042
13043                case PermissionInfo.PROTECTION_DANGEROUS: {
13044                    // If a permission review is required for legacy apps we represent
13045                    // their permissions as always granted runtime ones since we need
13046                    // to keep the review required permission flag per user while an
13047                    // install permission's state is shared across all users.
13048                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
13049                        // For legacy apps dangerous permissions are install time ones.
13050                        grant = GRANT_INSTALL;
13051                    } else if (origPermissions.hasInstallPermission(bp.name)) {
13052                        // For legacy apps that became modern, install becomes runtime.
13053                        grant = GRANT_UPGRADE;
13054                    } else if (mPromoteSystemApps
13055                            && isSystemApp(ps)
13056                            && mExistingSystemPackages.contains(ps.name)) {
13057                        // For legacy system apps, install becomes runtime.
13058                        // We cannot check hasInstallPermission() for system apps since those
13059                        // permissions were granted implicitly and not persisted pre-M.
13060                        grant = GRANT_UPGRADE;
13061                    } else {
13062                        // For modern apps keep runtime permissions unchanged.
13063                        grant = GRANT_RUNTIME;
13064                    }
13065                } break;
13066
13067                case PermissionInfo.PROTECTION_SIGNATURE: {
13068                    // For all apps signature permissions are install time ones.
13069                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
13070                    if (allowedSig) {
13071                        grant = GRANT_INSTALL;
13072                    }
13073                } break;
13074            }
13075
13076            if (DEBUG_PERMISSIONS) {
13077                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
13078            }
13079
13080            if (grant != GRANT_DENIED) {
13081                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
13082                    // If this is an existing, non-system package, then
13083                    // we can't add any new permissions to it.
13084                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
13085                        // Except...  if this is a permission that was added
13086                        // to the platform (note: need to only do this when
13087                        // updating the platform).
13088                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
13089                            grant = GRANT_DENIED;
13090                        }
13091                    }
13092                }
13093
13094                switch (grant) {
13095                    case GRANT_INSTALL: {
13096                        // Revoke this as runtime permission to handle the case of
13097                        // a runtime permission being downgraded to an install one.
13098                        // Also in permission review mode we keep dangerous permissions
13099                        // for legacy apps
13100                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13101                            if (origPermissions.getRuntimePermissionState(
13102                                    bp.name, userId) != null) {
13103                                // Revoke the runtime permission and clear the flags.
13104                                origPermissions.revokeRuntimePermission(bp, userId);
13105                                origPermissions.updatePermissionFlags(bp, userId,
13106                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
13107                                // If we revoked a permission permission, we have to write.
13108                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13109                                        changedRuntimePermissionUserIds, userId);
13110                            }
13111                        }
13112                        // Grant an install permission.
13113                        if (permissionsState.grantInstallPermission(bp) !=
13114                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13115                            changedInstallPermission = true;
13116                        }
13117                    } break;
13118
13119                    case GRANT_RUNTIME: {
13120                        // Grant previously granted runtime permissions.
13121                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13122                            PermissionState permissionState = origPermissions
13123                                    .getRuntimePermissionState(bp.name, userId);
13124                            int flags = permissionState != null
13125                                    ? permissionState.getFlags() : 0;
13126                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13127                                // Don't propagate the permission in a permission review mode if
13128                                // the former was revoked, i.e. marked to not propagate on upgrade.
13129                                // Note that in a permission review mode install permissions are
13130                                // represented as constantly granted runtime ones since we need to
13131                                // keep a per user state associated with the permission. Also the
13132                                // revoke on upgrade flag is no longer applicable and is reset.
13133                                final boolean revokeOnUpgrade = (flags & PackageManager
13134                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13135                                if (revokeOnUpgrade) {
13136                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13137                                    // Since we changed the flags, we have to write.
13138                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13139                                            changedRuntimePermissionUserIds, userId);
13140                                }
13141                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13142                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13143                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13144                                        // If we cannot put the permission as it was,
13145                                        // we have to write.
13146                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13147                                                changedRuntimePermissionUserIds, userId);
13148                                    }
13149                                }
13150
13151                                // If the app supports runtime permissions no need for a review.
13152                                if (mPermissionReviewRequired
13153                                        && appSupportsRuntimePermissions
13154                                        && (flags & PackageManager
13155                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13156                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13157                                    // Since we changed the flags, we have to write.
13158                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13159                                            changedRuntimePermissionUserIds, userId);
13160                                }
13161                            } else if (mPermissionReviewRequired
13162                                    && !appSupportsRuntimePermissions) {
13163                                // For legacy apps that need a permission review, every new
13164                                // runtime permission is granted but it is pending a review.
13165                                // We also need to review only platform defined runtime
13166                                // permissions as these are the only ones the platform knows
13167                                // how to disable the API to simulate revocation as legacy
13168                                // apps don't expect to run with revoked permissions.
13169                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13170                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13171                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13172                                        // We changed the flags, hence have to write.
13173                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13174                                                changedRuntimePermissionUserIds, userId);
13175                                    }
13176                                }
13177                                if (permissionsState.grantRuntimePermission(bp, userId)
13178                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13179                                    // We changed the permission, hence have to write.
13180                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13181                                            changedRuntimePermissionUserIds, userId);
13182                                }
13183                            }
13184                            // Propagate the permission flags.
13185                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13186                        }
13187                    } break;
13188
13189                    case GRANT_UPGRADE: {
13190                        // Grant runtime permissions for a previously held install permission.
13191                        PermissionState permissionState = origPermissions
13192                                .getInstallPermissionState(bp.name);
13193                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13194
13195                        if (origPermissions.revokeInstallPermission(bp)
13196                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13197                            // We will be transferring the permission flags, so clear them.
13198                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13199                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13200                            changedInstallPermission = true;
13201                        }
13202
13203                        // If the permission is not to be promoted to runtime we ignore it and
13204                        // also its other flags as they are not applicable to install permissions.
13205                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13206                            for (int userId : currentUserIds) {
13207                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13208                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13209                                    // Transfer the permission flags.
13210                                    permissionsState.updatePermissionFlags(bp, userId,
13211                                            flags, flags);
13212                                    // If we granted the permission, we have to write.
13213                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13214                                            changedRuntimePermissionUserIds, userId);
13215                                }
13216                            }
13217                        }
13218                    } break;
13219
13220                    default: {
13221                        if (packageOfInterest == null
13222                                || packageOfInterest.equals(pkg.packageName)) {
13223                            if (DEBUG_PERMISSIONS) {
13224                                Slog.i(TAG, "Not granting permission " + perm
13225                                        + " to package " + pkg.packageName
13226                                        + " because it was previously installed without");
13227                            }
13228                        }
13229                    } break;
13230                }
13231            } else {
13232                if (permissionsState.revokeInstallPermission(bp) !=
13233                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13234                    // Also drop the permission flags.
13235                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13236                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13237                    changedInstallPermission = true;
13238                    Slog.i(TAG, "Un-granting permission " + perm
13239                            + " from package " + pkg.packageName
13240                            + " (protectionLevel=" + bp.protectionLevel
13241                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13242                            + ")");
13243                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13244                    // Don't print warning for app op permissions, since it is fine for them
13245                    // not to be granted, there is a UI for the user to decide.
13246                    if (DEBUG_PERMISSIONS
13247                            && (packageOfInterest == null
13248                                    || packageOfInterest.equals(pkg.packageName))) {
13249                        Slog.i(TAG, "Not granting permission " + perm
13250                                + " to package " + pkg.packageName
13251                                + " (protectionLevel=" + bp.protectionLevel
13252                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13253                                + ")");
13254                    }
13255                }
13256            }
13257        }
13258
13259        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13260                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13261            // This is the first that we have heard about this package, so the
13262            // permissions we have now selected are fixed until explicitly
13263            // changed.
13264            ps.installPermissionsFixed = true;
13265        }
13266
13267        // Persist the runtime permissions state for users with changes. If permissions
13268        // were revoked because no app in the shared user declares them we have to
13269        // write synchronously to avoid losing runtime permissions state.
13270        for (int userId : changedRuntimePermissionUserIds) {
13271            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13272        }
13273    }
13274
13275    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13276        boolean allowed = false;
13277        final int NP = PackageParser.NEW_PERMISSIONS.length;
13278        for (int ip=0; ip<NP; ip++) {
13279            final PackageParser.NewPermissionInfo npi
13280                    = PackageParser.NEW_PERMISSIONS[ip];
13281            if (npi.name.equals(perm)
13282                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13283                allowed = true;
13284                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13285                        + pkg.packageName);
13286                break;
13287            }
13288        }
13289        return allowed;
13290    }
13291
13292    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13293            BasePermission bp, PermissionsState origPermissions) {
13294        boolean privilegedPermission = (bp.protectionLevel
13295                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13296        boolean privappPermissionsDisable =
13297                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13298        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13299        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13300        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13301                && !platformPackage && platformPermission) {
13302            final ArraySet<String> allowedPermissions = SystemConfig.getInstance()
13303                    .getPrivAppPermissions(pkg.packageName);
13304            final boolean whitelisted =
13305                    allowedPermissions != null && allowedPermissions.contains(perm);
13306            if (!whitelisted) {
13307                Slog.w(TAG, "Privileged permission " + perm + " for package "
13308                        + pkg.packageName + " - not in privapp-permissions whitelist");
13309                // Only report violations for apps on system image
13310                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13311                    // it's only a reportable violation if the permission isn't explicitly denied
13312                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13313                            .getPrivAppDenyPermissions(pkg.packageName);
13314                    final boolean permissionViolation =
13315                            deniedPermissions == null || !deniedPermissions.contains(perm);
13316                    if (permissionViolation) {
13317                        if (mPrivappPermissionsViolations == null) {
13318                            mPrivappPermissionsViolations = new ArraySet<>();
13319                        }
13320                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13321                    } else {
13322                        return false;
13323                    }
13324                }
13325                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13326                    return false;
13327                }
13328            }
13329        }
13330        boolean allowed = (compareSignatures(
13331                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13332                        == PackageManager.SIGNATURE_MATCH)
13333                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13334                        == PackageManager.SIGNATURE_MATCH);
13335        if (!allowed && privilegedPermission) {
13336            if (isSystemApp(pkg)) {
13337                // For updated system applications, a system permission
13338                // is granted only if it had been defined by the original application.
13339                if (pkg.isUpdatedSystemApp()) {
13340                    final PackageSetting sysPs = mSettings
13341                            .getDisabledSystemPkgLPr(pkg.packageName);
13342                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13343                        // If the original was granted this permission, we take
13344                        // that grant decision as read and propagate it to the
13345                        // update.
13346                        if (sysPs.isPrivileged()) {
13347                            allowed = true;
13348                        }
13349                    } else {
13350                        // The system apk may have been updated with an older
13351                        // version of the one on the data partition, but which
13352                        // granted a new system permission that it didn't have
13353                        // before.  In this case we do want to allow the app to
13354                        // now get the new permission if the ancestral apk is
13355                        // privileged to get it.
13356                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13357                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13358                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13359                                    allowed = true;
13360                                    break;
13361                                }
13362                            }
13363                        }
13364                        // Also if a privileged parent package on the system image or any of
13365                        // its children requested a privileged permission, the updated child
13366                        // packages can also get the permission.
13367                        if (pkg.parentPackage != null) {
13368                            final PackageSetting disabledSysParentPs = mSettings
13369                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13370                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13371                                    && disabledSysParentPs.isPrivileged()) {
13372                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13373                                    allowed = true;
13374                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13375                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13376                                    for (int i = 0; i < count; i++) {
13377                                        PackageParser.Package disabledSysChildPkg =
13378                                                disabledSysParentPs.pkg.childPackages.get(i);
13379                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13380                                                perm)) {
13381                                            allowed = true;
13382                                            break;
13383                                        }
13384                                    }
13385                                }
13386                            }
13387                        }
13388                    }
13389                } else {
13390                    allowed = isPrivilegedApp(pkg);
13391                }
13392            }
13393        }
13394        if (!allowed) {
13395            if (!allowed && (bp.protectionLevel
13396                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13397                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13398                // If this was a previously normal/dangerous permission that got moved
13399                // to a system permission as part of the runtime permission redesign, then
13400                // we still want to blindly grant it to old apps.
13401                allowed = true;
13402            }
13403            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13404                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13405                // If this permission is to be granted to the system installer and
13406                // this app is an installer, then it gets the permission.
13407                allowed = true;
13408            }
13409            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13410                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13411                // If this permission is to be granted to the system verifier and
13412                // this app is a verifier, then it gets the permission.
13413                allowed = true;
13414            }
13415            if (!allowed && (bp.protectionLevel
13416                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13417                    && isSystemApp(pkg)) {
13418                // Any pre-installed system app is allowed to get this permission.
13419                allowed = true;
13420            }
13421            if (!allowed && (bp.protectionLevel
13422                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13423                // For development permissions, a development permission
13424                // is granted only if it was already granted.
13425                allowed = origPermissions.hasInstallPermission(perm);
13426            }
13427            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13428                    && pkg.packageName.equals(mSetupWizardPackage)) {
13429                // If this permission is to be granted to the system setup wizard and
13430                // this app is a setup wizard, then it gets the permission.
13431                allowed = true;
13432            }
13433        }
13434        return allowed;
13435    }
13436
13437    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13438        final int permCount = pkg.requestedPermissions.size();
13439        for (int j = 0; j < permCount; j++) {
13440            String requestedPermission = pkg.requestedPermissions.get(j);
13441            if (permission.equals(requestedPermission)) {
13442                return true;
13443            }
13444        }
13445        return false;
13446    }
13447
13448    final class ActivityIntentResolver
13449            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13450        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13451                boolean defaultOnly, int userId) {
13452            if (!sUserManager.exists(userId)) return null;
13453            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13454            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13455        }
13456
13457        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13458                int userId) {
13459            if (!sUserManager.exists(userId)) return null;
13460            mFlags = flags;
13461            return super.queryIntent(intent, resolvedType,
13462                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13463                    userId);
13464        }
13465
13466        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13467                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13468            if (!sUserManager.exists(userId)) return null;
13469            if (packageActivities == null) {
13470                return null;
13471            }
13472            mFlags = flags;
13473            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13474            final int N = packageActivities.size();
13475            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13476                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13477
13478            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13479            for (int i = 0; i < N; ++i) {
13480                intentFilters = packageActivities.get(i).intents;
13481                if (intentFilters != null && intentFilters.size() > 0) {
13482                    PackageParser.ActivityIntentInfo[] array =
13483                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13484                    intentFilters.toArray(array);
13485                    listCut.add(array);
13486                }
13487            }
13488            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13489        }
13490
13491        /**
13492         * Finds a privileged activity that matches the specified activity names.
13493         */
13494        private PackageParser.Activity findMatchingActivity(
13495                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13496            for (PackageParser.Activity sysActivity : activityList) {
13497                if (sysActivity.info.name.equals(activityInfo.name)) {
13498                    return sysActivity;
13499                }
13500                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13501                    return sysActivity;
13502                }
13503                if (sysActivity.info.targetActivity != null) {
13504                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13505                        return sysActivity;
13506                    }
13507                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13508                        return sysActivity;
13509                    }
13510                }
13511            }
13512            return null;
13513        }
13514
13515        public class IterGenerator<E> {
13516            public Iterator<E> generate(ActivityIntentInfo info) {
13517                return null;
13518            }
13519        }
13520
13521        public class ActionIterGenerator extends IterGenerator<String> {
13522            @Override
13523            public Iterator<String> generate(ActivityIntentInfo info) {
13524                return info.actionsIterator();
13525            }
13526        }
13527
13528        public class CategoriesIterGenerator extends IterGenerator<String> {
13529            @Override
13530            public Iterator<String> generate(ActivityIntentInfo info) {
13531                return info.categoriesIterator();
13532            }
13533        }
13534
13535        public class SchemesIterGenerator extends IterGenerator<String> {
13536            @Override
13537            public Iterator<String> generate(ActivityIntentInfo info) {
13538                return info.schemesIterator();
13539            }
13540        }
13541
13542        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13543            @Override
13544            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13545                return info.authoritiesIterator();
13546            }
13547        }
13548
13549        /**
13550         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13551         * MODIFIED. Do not pass in a list that should not be changed.
13552         */
13553        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13554                IterGenerator<T> generator, Iterator<T> searchIterator) {
13555            // loop through the set of actions; every one must be found in the intent filter
13556            while (searchIterator.hasNext()) {
13557                // we must have at least one filter in the list to consider a match
13558                if (intentList.size() == 0) {
13559                    break;
13560                }
13561
13562                final T searchAction = searchIterator.next();
13563
13564                // loop through the set of intent filters
13565                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13566                while (intentIter.hasNext()) {
13567                    final ActivityIntentInfo intentInfo = intentIter.next();
13568                    boolean selectionFound = false;
13569
13570                    // loop through the intent filter's selection criteria; at least one
13571                    // of them must match the searched criteria
13572                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13573                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13574                        final T intentSelection = intentSelectionIter.next();
13575                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13576                            selectionFound = true;
13577                            break;
13578                        }
13579                    }
13580
13581                    // the selection criteria wasn't found in this filter's set; this filter
13582                    // is not a potential match
13583                    if (!selectionFound) {
13584                        intentIter.remove();
13585                    }
13586                }
13587            }
13588        }
13589
13590        private boolean isProtectedAction(ActivityIntentInfo filter) {
13591            final Iterator<String> actionsIter = filter.actionsIterator();
13592            while (actionsIter != null && actionsIter.hasNext()) {
13593                final String filterAction = actionsIter.next();
13594                if (PROTECTED_ACTIONS.contains(filterAction)) {
13595                    return true;
13596                }
13597            }
13598            return false;
13599        }
13600
13601        /**
13602         * Adjusts the priority of the given intent filter according to policy.
13603         * <p>
13604         * <ul>
13605         * <li>The priority for non privileged applications is capped to '0'</li>
13606         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13607         * <li>The priority for unbundled updates to privileged applications is capped to the
13608         *      priority defined on the system partition</li>
13609         * </ul>
13610         * <p>
13611         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13612         * allowed to obtain any priority on any action.
13613         */
13614        private void adjustPriority(
13615                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13616            // nothing to do; priority is fine as-is
13617            if (intent.getPriority() <= 0) {
13618                return;
13619            }
13620
13621            final ActivityInfo activityInfo = intent.activity.info;
13622            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13623
13624            final boolean privilegedApp =
13625                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13626            if (!privilegedApp) {
13627                // non-privileged applications can never define a priority >0
13628                if (DEBUG_FILTERS) {
13629                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13630                            + " package: " + applicationInfo.packageName
13631                            + " activity: " + intent.activity.className
13632                            + " origPrio: " + intent.getPriority());
13633                }
13634                intent.setPriority(0);
13635                return;
13636            }
13637
13638            if (systemActivities == null) {
13639                // the system package is not disabled; we're parsing the system partition
13640                if (isProtectedAction(intent)) {
13641                    if (mDeferProtectedFilters) {
13642                        // We can't deal with these just yet. No component should ever obtain a
13643                        // >0 priority for a protected actions, with ONE exception -- the setup
13644                        // wizard. The setup wizard, however, cannot be known until we're able to
13645                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13646                        // until all intent filters have been processed. Chicken, meet egg.
13647                        // Let the filter temporarily have a high priority and rectify the
13648                        // priorities after all system packages have been scanned.
13649                        mProtectedFilters.add(intent);
13650                        if (DEBUG_FILTERS) {
13651                            Slog.i(TAG, "Protected action; save for later;"
13652                                    + " package: " + applicationInfo.packageName
13653                                    + " activity: " + intent.activity.className
13654                                    + " origPrio: " + intent.getPriority());
13655                        }
13656                        return;
13657                    } else {
13658                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13659                            Slog.i(TAG, "No setup wizard;"
13660                                + " All protected intents capped to priority 0");
13661                        }
13662                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13663                            if (DEBUG_FILTERS) {
13664                                Slog.i(TAG, "Found setup wizard;"
13665                                    + " allow priority " + intent.getPriority() + ";"
13666                                    + " package: " + intent.activity.info.packageName
13667                                    + " activity: " + intent.activity.className
13668                                    + " priority: " + intent.getPriority());
13669                            }
13670                            // setup wizard gets whatever it wants
13671                            return;
13672                        }
13673                        if (DEBUG_FILTERS) {
13674                            Slog.i(TAG, "Protected action; cap priority to 0;"
13675                                    + " package: " + intent.activity.info.packageName
13676                                    + " activity: " + intent.activity.className
13677                                    + " origPrio: " + intent.getPriority());
13678                        }
13679                        intent.setPriority(0);
13680                        return;
13681                    }
13682                }
13683                // privileged apps on the system image get whatever priority they request
13684                return;
13685            }
13686
13687            // privileged app unbundled update ... try to find the same activity
13688            final PackageParser.Activity foundActivity =
13689                    findMatchingActivity(systemActivities, activityInfo);
13690            if (foundActivity == null) {
13691                // this is a new activity; it cannot obtain >0 priority
13692                if (DEBUG_FILTERS) {
13693                    Slog.i(TAG, "New activity; cap priority to 0;"
13694                            + " package: " + applicationInfo.packageName
13695                            + " activity: " + intent.activity.className
13696                            + " origPrio: " + intent.getPriority());
13697                }
13698                intent.setPriority(0);
13699                return;
13700            }
13701
13702            // found activity, now check for filter equivalence
13703
13704            // a shallow copy is enough; we modify the list, not its contents
13705            final List<ActivityIntentInfo> intentListCopy =
13706                    new ArrayList<>(foundActivity.intents);
13707            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13708
13709            // find matching action subsets
13710            final Iterator<String> actionsIterator = intent.actionsIterator();
13711            if (actionsIterator != null) {
13712                getIntentListSubset(
13713                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13714                if (intentListCopy.size() == 0) {
13715                    // no more intents to match; we're not equivalent
13716                    if (DEBUG_FILTERS) {
13717                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13718                                + " package: " + applicationInfo.packageName
13719                                + " activity: " + intent.activity.className
13720                                + " origPrio: " + intent.getPriority());
13721                    }
13722                    intent.setPriority(0);
13723                    return;
13724                }
13725            }
13726
13727            // find matching category subsets
13728            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13729            if (categoriesIterator != null) {
13730                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13731                        categoriesIterator);
13732                if (intentListCopy.size() == 0) {
13733                    // no more intents to match; we're not equivalent
13734                    if (DEBUG_FILTERS) {
13735                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13736                                + " package: " + applicationInfo.packageName
13737                                + " activity: " + intent.activity.className
13738                                + " origPrio: " + intent.getPriority());
13739                    }
13740                    intent.setPriority(0);
13741                    return;
13742                }
13743            }
13744
13745            // find matching schemes subsets
13746            final Iterator<String> schemesIterator = intent.schemesIterator();
13747            if (schemesIterator != null) {
13748                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13749                        schemesIterator);
13750                if (intentListCopy.size() == 0) {
13751                    // no more intents to match; we're not equivalent
13752                    if (DEBUG_FILTERS) {
13753                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13754                                + " package: " + applicationInfo.packageName
13755                                + " activity: " + intent.activity.className
13756                                + " origPrio: " + intent.getPriority());
13757                    }
13758                    intent.setPriority(0);
13759                    return;
13760                }
13761            }
13762
13763            // find matching authorities subsets
13764            final Iterator<IntentFilter.AuthorityEntry>
13765                    authoritiesIterator = intent.authoritiesIterator();
13766            if (authoritiesIterator != null) {
13767                getIntentListSubset(intentListCopy,
13768                        new AuthoritiesIterGenerator(),
13769                        authoritiesIterator);
13770                if (intentListCopy.size() == 0) {
13771                    // no more intents to match; we're not equivalent
13772                    if (DEBUG_FILTERS) {
13773                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13774                                + " package: " + applicationInfo.packageName
13775                                + " activity: " + intent.activity.className
13776                                + " origPrio: " + intent.getPriority());
13777                    }
13778                    intent.setPriority(0);
13779                    return;
13780                }
13781            }
13782
13783            // we found matching filter(s); app gets the max priority of all intents
13784            int cappedPriority = 0;
13785            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13786                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13787            }
13788            if (intent.getPriority() > cappedPriority) {
13789                if (DEBUG_FILTERS) {
13790                    Slog.i(TAG, "Found matching filter(s);"
13791                            + " cap priority to " + cappedPriority + ";"
13792                            + " package: " + applicationInfo.packageName
13793                            + " activity: " + intent.activity.className
13794                            + " origPrio: " + intent.getPriority());
13795                }
13796                intent.setPriority(cappedPriority);
13797                return;
13798            }
13799            // all this for nothing; the requested priority was <= what was on the system
13800        }
13801
13802        public final void addActivity(PackageParser.Activity a, String type) {
13803            mActivities.put(a.getComponentName(), a);
13804            if (DEBUG_SHOW_INFO)
13805                Log.v(
13806                TAG, "  " + type + " " +
13807                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13808            if (DEBUG_SHOW_INFO)
13809                Log.v(TAG, "    Class=" + a.info.name);
13810            final int NI = a.intents.size();
13811            for (int j=0; j<NI; j++) {
13812                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13813                if ("activity".equals(type)) {
13814                    final PackageSetting ps =
13815                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13816                    final List<PackageParser.Activity> systemActivities =
13817                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13818                    adjustPriority(systemActivities, intent);
13819                }
13820                if (DEBUG_SHOW_INFO) {
13821                    Log.v(TAG, "    IntentFilter:");
13822                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13823                }
13824                if (!intent.debugCheck()) {
13825                    Log.w(TAG, "==> For Activity " + a.info.name);
13826                }
13827                addFilter(intent);
13828            }
13829        }
13830
13831        public final void removeActivity(PackageParser.Activity a, String type) {
13832            mActivities.remove(a.getComponentName());
13833            if (DEBUG_SHOW_INFO) {
13834                Log.v(TAG, "  " + type + " "
13835                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13836                                : a.info.name) + ":");
13837                Log.v(TAG, "    Class=" + a.info.name);
13838            }
13839            final int NI = a.intents.size();
13840            for (int j=0; j<NI; j++) {
13841                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13842                if (DEBUG_SHOW_INFO) {
13843                    Log.v(TAG, "    IntentFilter:");
13844                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13845                }
13846                removeFilter(intent);
13847            }
13848        }
13849
13850        @Override
13851        protected boolean allowFilterResult(
13852                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13853            ActivityInfo filterAi = filter.activity.info;
13854            for (int i=dest.size()-1; i>=0; i--) {
13855                ActivityInfo destAi = dest.get(i).activityInfo;
13856                if (destAi.name == filterAi.name
13857                        && destAi.packageName == filterAi.packageName) {
13858                    return false;
13859                }
13860            }
13861            return true;
13862        }
13863
13864        @Override
13865        protected ActivityIntentInfo[] newArray(int size) {
13866            return new ActivityIntentInfo[size];
13867        }
13868
13869        @Override
13870        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13871            if (!sUserManager.exists(userId)) return true;
13872            PackageParser.Package p = filter.activity.owner;
13873            if (p != null) {
13874                PackageSetting ps = (PackageSetting)p.mExtras;
13875                if (ps != null) {
13876                    // System apps are never considered stopped for purposes of
13877                    // filtering, because there may be no way for the user to
13878                    // actually re-launch them.
13879                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13880                            && ps.getStopped(userId);
13881                }
13882            }
13883            return false;
13884        }
13885
13886        @Override
13887        protected boolean isPackageForFilter(String packageName,
13888                PackageParser.ActivityIntentInfo info) {
13889            return packageName.equals(info.activity.owner.packageName);
13890        }
13891
13892        @Override
13893        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13894                int match, int userId) {
13895            if (!sUserManager.exists(userId)) return null;
13896            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13897                return null;
13898            }
13899            final PackageParser.Activity activity = info.activity;
13900            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13901            if (ps == null) {
13902                return null;
13903            }
13904            final PackageUserState userState = ps.readUserState(userId);
13905            ActivityInfo ai =
13906                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13907            if (ai == null) {
13908                return null;
13909            }
13910            final boolean matchExplicitlyVisibleOnly =
13911                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13912            final boolean matchVisibleToInstantApp =
13913                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13914            final boolean componentVisible =
13915                    matchVisibleToInstantApp
13916                    && info.isVisibleToInstantApp()
13917                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13918            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13919            // throw out filters that aren't visible to ephemeral apps
13920            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13921                return null;
13922            }
13923            // throw out instant app filters if we're not explicitly requesting them
13924            if (!matchInstantApp && userState.instantApp) {
13925                return null;
13926            }
13927            // throw out instant app filters if updates are available; will trigger
13928            // instant app resolution
13929            if (userState.instantApp && ps.isUpdateAvailable()) {
13930                return null;
13931            }
13932            final ResolveInfo res = new ResolveInfo();
13933            res.activityInfo = ai;
13934            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13935                res.filter = info;
13936            }
13937            if (info != null) {
13938                res.handleAllWebDataURI = info.handleAllWebDataURI();
13939            }
13940            res.priority = info.getPriority();
13941            res.preferredOrder = activity.owner.mPreferredOrder;
13942            //System.out.println("Result: " + res.activityInfo.className +
13943            //                   " = " + res.priority);
13944            res.match = match;
13945            res.isDefault = info.hasDefault;
13946            res.labelRes = info.labelRes;
13947            res.nonLocalizedLabel = info.nonLocalizedLabel;
13948            if (userNeedsBadging(userId)) {
13949                res.noResourceId = true;
13950            } else {
13951                res.icon = info.icon;
13952            }
13953            res.iconResourceId = info.icon;
13954            res.system = res.activityInfo.applicationInfo.isSystemApp();
13955            res.isInstantAppAvailable = userState.instantApp;
13956            return res;
13957        }
13958
13959        @Override
13960        protected void sortResults(List<ResolveInfo> results) {
13961            Collections.sort(results, mResolvePrioritySorter);
13962        }
13963
13964        @Override
13965        protected void dumpFilter(PrintWriter out, String prefix,
13966                PackageParser.ActivityIntentInfo filter) {
13967            out.print(prefix); out.print(
13968                    Integer.toHexString(System.identityHashCode(filter.activity)));
13969                    out.print(' ');
13970                    filter.activity.printComponentShortName(out);
13971                    out.print(" filter ");
13972                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13973        }
13974
13975        @Override
13976        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13977            return filter.activity;
13978        }
13979
13980        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13981            PackageParser.Activity activity = (PackageParser.Activity)label;
13982            out.print(prefix); out.print(
13983                    Integer.toHexString(System.identityHashCode(activity)));
13984                    out.print(' ');
13985                    activity.printComponentShortName(out);
13986            if (count > 1) {
13987                out.print(" ("); out.print(count); out.print(" filters)");
13988            }
13989            out.println();
13990        }
13991
13992        // Keys are String (activity class name), values are Activity.
13993        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13994                = new ArrayMap<ComponentName, PackageParser.Activity>();
13995        private int mFlags;
13996    }
13997
13998    private final class ServiceIntentResolver
13999            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
14000        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14001                boolean defaultOnly, int userId) {
14002            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14003            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14004        }
14005
14006        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14007                int userId) {
14008            if (!sUserManager.exists(userId)) return null;
14009            mFlags = flags;
14010            return super.queryIntent(intent, resolvedType,
14011                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14012                    userId);
14013        }
14014
14015        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14016                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
14017            if (!sUserManager.exists(userId)) return null;
14018            if (packageServices == null) {
14019                return null;
14020            }
14021            mFlags = flags;
14022            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
14023            final int N = packageServices.size();
14024            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
14025                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
14026
14027            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
14028            for (int i = 0; i < N; ++i) {
14029                intentFilters = packageServices.get(i).intents;
14030                if (intentFilters != null && intentFilters.size() > 0) {
14031                    PackageParser.ServiceIntentInfo[] array =
14032                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
14033                    intentFilters.toArray(array);
14034                    listCut.add(array);
14035                }
14036            }
14037            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14038        }
14039
14040        public final void addService(PackageParser.Service s) {
14041            mServices.put(s.getComponentName(), s);
14042            if (DEBUG_SHOW_INFO) {
14043                Log.v(TAG, "  "
14044                        + (s.info.nonLocalizedLabel != null
14045                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14046                Log.v(TAG, "    Class=" + s.info.name);
14047            }
14048            final int NI = s.intents.size();
14049            int j;
14050            for (j=0; j<NI; j++) {
14051                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14052                if (DEBUG_SHOW_INFO) {
14053                    Log.v(TAG, "    IntentFilter:");
14054                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14055                }
14056                if (!intent.debugCheck()) {
14057                    Log.w(TAG, "==> For Service " + s.info.name);
14058                }
14059                addFilter(intent);
14060            }
14061        }
14062
14063        public final void removeService(PackageParser.Service s) {
14064            mServices.remove(s.getComponentName());
14065            if (DEBUG_SHOW_INFO) {
14066                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
14067                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14068                Log.v(TAG, "    Class=" + s.info.name);
14069            }
14070            final int NI = s.intents.size();
14071            int j;
14072            for (j=0; j<NI; j++) {
14073                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14074                if (DEBUG_SHOW_INFO) {
14075                    Log.v(TAG, "    IntentFilter:");
14076                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14077                }
14078                removeFilter(intent);
14079            }
14080        }
14081
14082        @Override
14083        protected boolean allowFilterResult(
14084                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
14085            ServiceInfo filterSi = filter.service.info;
14086            for (int i=dest.size()-1; i>=0; i--) {
14087                ServiceInfo destAi = dest.get(i).serviceInfo;
14088                if (destAi.name == filterSi.name
14089                        && destAi.packageName == filterSi.packageName) {
14090                    return false;
14091                }
14092            }
14093            return true;
14094        }
14095
14096        @Override
14097        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
14098            return new PackageParser.ServiceIntentInfo[size];
14099        }
14100
14101        @Override
14102        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
14103            if (!sUserManager.exists(userId)) return true;
14104            PackageParser.Package p = filter.service.owner;
14105            if (p != null) {
14106                PackageSetting ps = (PackageSetting)p.mExtras;
14107                if (ps != null) {
14108                    // System apps are never considered stopped for purposes of
14109                    // filtering, because there may be no way for the user to
14110                    // actually re-launch them.
14111                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14112                            && ps.getStopped(userId);
14113                }
14114            }
14115            return false;
14116        }
14117
14118        @Override
14119        protected boolean isPackageForFilter(String packageName,
14120                PackageParser.ServiceIntentInfo info) {
14121            return packageName.equals(info.service.owner.packageName);
14122        }
14123
14124        @Override
14125        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14126                int match, int userId) {
14127            if (!sUserManager.exists(userId)) return null;
14128            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14129            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14130                return null;
14131            }
14132            final PackageParser.Service service = info.service;
14133            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14134            if (ps == null) {
14135                return null;
14136            }
14137            final PackageUserState userState = ps.readUserState(userId);
14138            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14139                    userState, userId);
14140            if (si == null) {
14141                return null;
14142            }
14143            final boolean matchVisibleToInstantApp =
14144                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14145            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14146            // throw out filters that aren't visible to ephemeral apps
14147            if (matchVisibleToInstantApp
14148                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14149                return null;
14150            }
14151            // throw out ephemeral filters if we're not explicitly requesting them
14152            if (!isInstantApp && userState.instantApp) {
14153                return null;
14154            }
14155            // throw out instant app filters if updates are available; will trigger
14156            // instant app resolution
14157            if (userState.instantApp && ps.isUpdateAvailable()) {
14158                return null;
14159            }
14160            final ResolveInfo res = new ResolveInfo();
14161            res.serviceInfo = si;
14162            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14163                res.filter = filter;
14164            }
14165            res.priority = info.getPriority();
14166            res.preferredOrder = service.owner.mPreferredOrder;
14167            res.match = match;
14168            res.isDefault = info.hasDefault;
14169            res.labelRes = info.labelRes;
14170            res.nonLocalizedLabel = info.nonLocalizedLabel;
14171            res.icon = info.icon;
14172            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14173            return res;
14174        }
14175
14176        @Override
14177        protected void sortResults(List<ResolveInfo> results) {
14178            Collections.sort(results, mResolvePrioritySorter);
14179        }
14180
14181        @Override
14182        protected void dumpFilter(PrintWriter out, String prefix,
14183                PackageParser.ServiceIntentInfo filter) {
14184            out.print(prefix); out.print(
14185                    Integer.toHexString(System.identityHashCode(filter.service)));
14186                    out.print(' ');
14187                    filter.service.printComponentShortName(out);
14188                    out.print(" filter ");
14189                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14190        }
14191
14192        @Override
14193        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14194            return filter.service;
14195        }
14196
14197        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14198            PackageParser.Service service = (PackageParser.Service)label;
14199            out.print(prefix); out.print(
14200                    Integer.toHexString(System.identityHashCode(service)));
14201                    out.print(' ');
14202                    service.printComponentShortName(out);
14203            if (count > 1) {
14204                out.print(" ("); out.print(count); out.print(" filters)");
14205            }
14206            out.println();
14207        }
14208
14209//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14210//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14211//            final List<ResolveInfo> retList = Lists.newArrayList();
14212//            while (i.hasNext()) {
14213//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14214//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14215//                    retList.add(resolveInfo);
14216//                }
14217//            }
14218//            return retList;
14219//        }
14220
14221        // Keys are String (activity class name), values are Activity.
14222        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14223                = new ArrayMap<ComponentName, PackageParser.Service>();
14224        private int mFlags;
14225    }
14226
14227    private final class ProviderIntentResolver
14228            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14229        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14230                boolean defaultOnly, int userId) {
14231            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14232            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14233        }
14234
14235        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14236                int userId) {
14237            if (!sUserManager.exists(userId))
14238                return null;
14239            mFlags = flags;
14240            return super.queryIntent(intent, resolvedType,
14241                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14242                    userId);
14243        }
14244
14245        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14246                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14247            if (!sUserManager.exists(userId))
14248                return null;
14249            if (packageProviders == null) {
14250                return null;
14251            }
14252            mFlags = flags;
14253            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14254            final int N = packageProviders.size();
14255            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14256                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14257
14258            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14259            for (int i = 0; i < N; ++i) {
14260                intentFilters = packageProviders.get(i).intents;
14261                if (intentFilters != null && intentFilters.size() > 0) {
14262                    PackageParser.ProviderIntentInfo[] array =
14263                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14264                    intentFilters.toArray(array);
14265                    listCut.add(array);
14266                }
14267            }
14268            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14269        }
14270
14271        public final void addProvider(PackageParser.Provider p) {
14272            if (mProviders.containsKey(p.getComponentName())) {
14273                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14274                return;
14275            }
14276
14277            mProviders.put(p.getComponentName(), p);
14278            if (DEBUG_SHOW_INFO) {
14279                Log.v(TAG, "  "
14280                        + (p.info.nonLocalizedLabel != null
14281                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14282                Log.v(TAG, "    Class=" + p.info.name);
14283            }
14284            final int NI = p.intents.size();
14285            int j;
14286            for (j = 0; j < NI; j++) {
14287                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14288                if (DEBUG_SHOW_INFO) {
14289                    Log.v(TAG, "    IntentFilter:");
14290                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14291                }
14292                if (!intent.debugCheck()) {
14293                    Log.w(TAG, "==> For Provider " + p.info.name);
14294                }
14295                addFilter(intent);
14296            }
14297        }
14298
14299        public final void removeProvider(PackageParser.Provider p) {
14300            mProviders.remove(p.getComponentName());
14301            if (DEBUG_SHOW_INFO) {
14302                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14303                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14304                Log.v(TAG, "    Class=" + p.info.name);
14305            }
14306            final int NI = p.intents.size();
14307            int j;
14308            for (j = 0; j < NI; j++) {
14309                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14310                if (DEBUG_SHOW_INFO) {
14311                    Log.v(TAG, "    IntentFilter:");
14312                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14313                }
14314                removeFilter(intent);
14315            }
14316        }
14317
14318        @Override
14319        protected boolean allowFilterResult(
14320                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14321            ProviderInfo filterPi = filter.provider.info;
14322            for (int i = dest.size() - 1; i >= 0; i--) {
14323                ProviderInfo destPi = dest.get(i).providerInfo;
14324                if (destPi.name == filterPi.name
14325                        && destPi.packageName == filterPi.packageName) {
14326                    return false;
14327                }
14328            }
14329            return true;
14330        }
14331
14332        @Override
14333        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14334            return new PackageParser.ProviderIntentInfo[size];
14335        }
14336
14337        @Override
14338        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14339            if (!sUserManager.exists(userId))
14340                return true;
14341            PackageParser.Package p = filter.provider.owner;
14342            if (p != null) {
14343                PackageSetting ps = (PackageSetting) p.mExtras;
14344                if (ps != null) {
14345                    // System apps are never considered stopped for purposes of
14346                    // filtering, because there may be no way for the user to
14347                    // actually re-launch them.
14348                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14349                            && ps.getStopped(userId);
14350                }
14351            }
14352            return false;
14353        }
14354
14355        @Override
14356        protected boolean isPackageForFilter(String packageName,
14357                PackageParser.ProviderIntentInfo info) {
14358            return packageName.equals(info.provider.owner.packageName);
14359        }
14360
14361        @Override
14362        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14363                int match, int userId) {
14364            if (!sUserManager.exists(userId))
14365                return null;
14366            final PackageParser.ProviderIntentInfo info = filter;
14367            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14368                return null;
14369            }
14370            final PackageParser.Provider provider = info.provider;
14371            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14372            if (ps == null) {
14373                return null;
14374            }
14375            final PackageUserState userState = ps.readUserState(userId);
14376            final boolean matchVisibleToInstantApp =
14377                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14378            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14379            // throw out filters that aren't visible to instant applications
14380            if (matchVisibleToInstantApp
14381                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14382                return null;
14383            }
14384            // throw out instant application filters if we're not explicitly requesting them
14385            if (!isInstantApp && userState.instantApp) {
14386                return null;
14387            }
14388            // throw out instant application filters if updates are available; will trigger
14389            // instant application resolution
14390            if (userState.instantApp && ps.isUpdateAvailable()) {
14391                return null;
14392            }
14393            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14394                    userState, userId);
14395            if (pi == null) {
14396                return null;
14397            }
14398            final ResolveInfo res = new ResolveInfo();
14399            res.providerInfo = pi;
14400            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14401                res.filter = filter;
14402            }
14403            res.priority = info.getPriority();
14404            res.preferredOrder = provider.owner.mPreferredOrder;
14405            res.match = match;
14406            res.isDefault = info.hasDefault;
14407            res.labelRes = info.labelRes;
14408            res.nonLocalizedLabel = info.nonLocalizedLabel;
14409            res.icon = info.icon;
14410            res.system = res.providerInfo.applicationInfo.isSystemApp();
14411            return res;
14412        }
14413
14414        @Override
14415        protected void sortResults(List<ResolveInfo> results) {
14416            Collections.sort(results, mResolvePrioritySorter);
14417        }
14418
14419        @Override
14420        protected void dumpFilter(PrintWriter out, String prefix,
14421                PackageParser.ProviderIntentInfo filter) {
14422            out.print(prefix);
14423            out.print(
14424                    Integer.toHexString(System.identityHashCode(filter.provider)));
14425            out.print(' ');
14426            filter.provider.printComponentShortName(out);
14427            out.print(" filter ");
14428            out.println(Integer.toHexString(System.identityHashCode(filter)));
14429        }
14430
14431        @Override
14432        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14433            return filter.provider;
14434        }
14435
14436        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14437            PackageParser.Provider provider = (PackageParser.Provider)label;
14438            out.print(prefix); out.print(
14439                    Integer.toHexString(System.identityHashCode(provider)));
14440                    out.print(' ');
14441                    provider.printComponentShortName(out);
14442            if (count > 1) {
14443                out.print(" ("); out.print(count); out.print(" filters)");
14444            }
14445            out.println();
14446        }
14447
14448        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14449                = new ArrayMap<ComponentName, PackageParser.Provider>();
14450        private int mFlags;
14451    }
14452
14453    static final class EphemeralIntentResolver
14454            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14455        /**
14456         * The result that has the highest defined order. Ordering applies on a
14457         * per-package basis. Mapping is from package name to Pair of order and
14458         * EphemeralResolveInfo.
14459         * <p>
14460         * NOTE: This is implemented as a field variable for convenience and efficiency.
14461         * By having a field variable, we're able to track filter ordering as soon as
14462         * a non-zero order is defined. Otherwise, multiple loops across the result set
14463         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14464         * this needs to be contained entirely within {@link #filterResults}.
14465         */
14466        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14467
14468        @Override
14469        protected AuxiliaryResolveInfo[] newArray(int size) {
14470            return new AuxiliaryResolveInfo[size];
14471        }
14472
14473        @Override
14474        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14475            return true;
14476        }
14477
14478        @Override
14479        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14480                int userId) {
14481            if (!sUserManager.exists(userId)) {
14482                return null;
14483            }
14484            final String packageName = responseObj.resolveInfo.getPackageName();
14485            final Integer order = responseObj.getOrder();
14486            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14487                    mOrderResult.get(packageName);
14488            // ordering is enabled and this item's order isn't high enough
14489            if (lastOrderResult != null && lastOrderResult.first >= order) {
14490                return null;
14491            }
14492            final InstantAppResolveInfo res = responseObj.resolveInfo;
14493            if (order > 0) {
14494                // non-zero order, enable ordering
14495                mOrderResult.put(packageName, new Pair<>(order, res));
14496            }
14497            return responseObj;
14498        }
14499
14500        @Override
14501        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14502            // only do work if ordering is enabled [most of the time it won't be]
14503            if (mOrderResult.size() == 0) {
14504                return;
14505            }
14506            int resultSize = results.size();
14507            for (int i = 0; i < resultSize; i++) {
14508                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14509                final String packageName = info.getPackageName();
14510                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14511                if (savedInfo == null) {
14512                    // package doesn't having ordering
14513                    continue;
14514                }
14515                if (savedInfo.second == info) {
14516                    // circled back to the highest ordered item; remove from order list
14517                    mOrderResult.remove(packageName);
14518                    if (mOrderResult.size() == 0) {
14519                        // no more ordered items
14520                        break;
14521                    }
14522                    continue;
14523                }
14524                // item has a worse order, remove it from the result list
14525                results.remove(i);
14526                resultSize--;
14527                i--;
14528            }
14529        }
14530    }
14531
14532    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14533            new Comparator<ResolveInfo>() {
14534        public int compare(ResolveInfo r1, ResolveInfo r2) {
14535            int v1 = r1.priority;
14536            int v2 = r2.priority;
14537            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14538            if (v1 != v2) {
14539                return (v1 > v2) ? -1 : 1;
14540            }
14541            v1 = r1.preferredOrder;
14542            v2 = r2.preferredOrder;
14543            if (v1 != v2) {
14544                return (v1 > v2) ? -1 : 1;
14545            }
14546            if (r1.isDefault != r2.isDefault) {
14547                return r1.isDefault ? -1 : 1;
14548            }
14549            v1 = r1.match;
14550            v2 = r2.match;
14551            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14552            if (v1 != v2) {
14553                return (v1 > v2) ? -1 : 1;
14554            }
14555            if (r1.system != r2.system) {
14556                return r1.system ? -1 : 1;
14557            }
14558            if (r1.activityInfo != null) {
14559                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14560            }
14561            if (r1.serviceInfo != null) {
14562                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14563            }
14564            if (r1.providerInfo != null) {
14565                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14566            }
14567            return 0;
14568        }
14569    };
14570
14571    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14572            new Comparator<ProviderInfo>() {
14573        public int compare(ProviderInfo p1, ProviderInfo p2) {
14574            final int v1 = p1.initOrder;
14575            final int v2 = p2.initOrder;
14576            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14577        }
14578    };
14579
14580    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14581            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14582            final int[] userIds) {
14583        mHandler.post(new Runnable() {
14584            @Override
14585            public void run() {
14586                try {
14587                    final IActivityManager am = ActivityManager.getService();
14588                    if (am == null) return;
14589                    final int[] resolvedUserIds;
14590                    if (userIds == null) {
14591                        resolvedUserIds = am.getRunningUserIds();
14592                    } else {
14593                        resolvedUserIds = userIds;
14594                    }
14595                    for (int id : resolvedUserIds) {
14596                        final Intent intent = new Intent(action,
14597                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14598                        if (extras != null) {
14599                            intent.putExtras(extras);
14600                        }
14601                        if (targetPkg != null) {
14602                            intent.setPackage(targetPkg);
14603                        }
14604                        // Modify the UID when posting to other users
14605                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14606                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14607                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14608                            intent.putExtra(Intent.EXTRA_UID, uid);
14609                        }
14610                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14611                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14612                        if (DEBUG_BROADCASTS) {
14613                            RuntimeException here = new RuntimeException("here");
14614                            here.fillInStackTrace();
14615                            Slog.d(TAG, "Sending to user " + id + ": "
14616                                    + intent.toShortString(false, true, false, false)
14617                                    + " " + intent.getExtras(), here);
14618                        }
14619                        am.broadcastIntent(null, intent, null, finishedReceiver,
14620                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14621                                null, finishedReceiver != null, false, id);
14622                    }
14623                } catch (RemoteException ex) {
14624                }
14625            }
14626        });
14627    }
14628
14629    /**
14630     * Check if the external storage media is available. This is true if there
14631     * is a mounted external storage medium or if the external storage is
14632     * emulated.
14633     */
14634    private boolean isExternalMediaAvailable() {
14635        return mMediaMounted || Environment.isExternalStorageEmulated();
14636    }
14637
14638    @Override
14639    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14640        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14641            return null;
14642        }
14643        if (!isExternalMediaAvailable()) {
14644                // If the external storage is no longer mounted at this point,
14645                // the caller may not have been able to delete all of this
14646                // packages files and can not delete any more.  Bail.
14647            return null;
14648        }
14649        synchronized (mPackages) {
14650            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14651            if (lastPackage != null) {
14652                pkgs.remove(lastPackage);
14653            }
14654            if (pkgs.size() > 0) {
14655                return pkgs.get(0);
14656            }
14657        }
14658        return null;
14659    }
14660
14661    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14662        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14663                userId, andCode ? 1 : 0, packageName);
14664        if (mSystemReady) {
14665            msg.sendToTarget();
14666        } else {
14667            if (mPostSystemReadyMessages == null) {
14668                mPostSystemReadyMessages = new ArrayList<>();
14669            }
14670            mPostSystemReadyMessages.add(msg);
14671        }
14672    }
14673
14674    void startCleaningPackages() {
14675        // reader
14676        if (!isExternalMediaAvailable()) {
14677            return;
14678        }
14679        synchronized (mPackages) {
14680            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14681                return;
14682            }
14683        }
14684        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14685        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14686        IActivityManager am = ActivityManager.getService();
14687        if (am != null) {
14688            int dcsUid = -1;
14689            synchronized (mPackages) {
14690                if (!mDefaultContainerWhitelisted) {
14691                    mDefaultContainerWhitelisted = true;
14692                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14693                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14694                }
14695            }
14696            try {
14697                if (dcsUid > 0) {
14698                    am.backgroundWhitelistUid(dcsUid);
14699                }
14700                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14701                        UserHandle.USER_SYSTEM);
14702            } catch (RemoteException e) {
14703            }
14704        }
14705    }
14706
14707    @Override
14708    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14709            int installFlags, String installerPackageName, int userId) {
14710        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14711
14712        final int callingUid = Binder.getCallingUid();
14713        enforceCrossUserPermission(callingUid, userId,
14714                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14715
14716        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14717            try {
14718                if (observer != null) {
14719                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14720                }
14721            } catch (RemoteException re) {
14722            }
14723            return;
14724        }
14725
14726        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14727            installFlags |= PackageManager.INSTALL_FROM_ADB;
14728
14729        } else {
14730            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14731            // about installerPackageName.
14732
14733            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14734            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14735        }
14736
14737        UserHandle user;
14738        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14739            user = UserHandle.ALL;
14740        } else {
14741            user = new UserHandle(userId);
14742        }
14743
14744        // Only system components can circumvent runtime permissions when installing.
14745        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14746                && mContext.checkCallingOrSelfPermission(Manifest.permission
14747                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14748            throw new SecurityException("You need the "
14749                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14750                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14751        }
14752
14753        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14754                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14755            throw new IllegalArgumentException(
14756                    "New installs into ASEC containers no longer supported");
14757        }
14758
14759        final File originFile = new File(originPath);
14760        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14761
14762        final Message msg = mHandler.obtainMessage(INIT_COPY);
14763        final VerificationInfo verificationInfo = new VerificationInfo(
14764                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14765        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14766                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14767                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14768                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14769        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14770        msg.obj = params;
14771
14772        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14773                System.identityHashCode(msg.obj));
14774        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14775                System.identityHashCode(msg.obj));
14776
14777        mHandler.sendMessage(msg);
14778    }
14779
14780
14781    /**
14782     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14783     * it is acting on behalf on an enterprise or the user).
14784     *
14785     * Note that the ordering of the conditionals in this method is important. The checks we perform
14786     * are as follows, in this order:
14787     *
14788     * 1) If the install is being performed by a system app, we can trust the app to have set the
14789     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14790     *    what it is.
14791     * 2) If the install is being performed by a device or profile owner app, the install reason
14792     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14793     *    set the install reason correctly. If the app targets an older SDK version where install
14794     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14795     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14796     * 3) In all other cases, the install is being performed by a regular app that is neither part
14797     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14798     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14799     *    set to enterprise policy and if so, change it to unknown instead.
14800     */
14801    private int fixUpInstallReason(String installerPackageName, int installerUid,
14802            int installReason) {
14803        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14804                == PERMISSION_GRANTED) {
14805            // If the install is being performed by a system app, we trust that app to have set the
14806            // install reason correctly.
14807            return installReason;
14808        }
14809
14810        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14811            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14812        if (dpm != null) {
14813            ComponentName owner = null;
14814            try {
14815                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14816                if (owner == null) {
14817                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14818                }
14819            } catch (RemoteException e) {
14820            }
14821            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14822                // If the install is being performed by a device or profile owner, the install
14823                // reason should be enterprise policy.
14824                return PackageManager.INSTALL_REASON_POLICY;
14825            }
14826        }
14827
14828        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14829            // If the install is being performed by a regular app (i.e. neither system app nor
14830            // device or profile owner), we have no reason to believe that the app is acting on
14831            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14832            // change it to unknown instead.
14833            return PackageManager.INSTALL_REASON_UNKNOWN;
14834        }
14835
14836        // If the install is being performed by a regular app and the install reason was set to any
14837        // value but enterprise policy, leave the install reason unchanged.
14838        return installReason;
14839    }
14840
14841    void installStage(String packageName, File stagedDir, String stagedCid,
14842            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14843            String installerPackageName, int installerUid, UserHandle user,
14844            Certificate[][] certificates) {
14845        if (DEBUG_EPHEMERAL) {
14846            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14847                Slog.d(TAG, "Ephemeral install of " + packageName);
14848            }
14849        }
14850        final VerificationInfo verificationInfo = new VerificationInfo(
14851                sessionParams.originatingUri, sessionParams.referrerUri,
14852                sessionParams.originatingUid, installerUid);
14853
14854        final OriginInfo origin;
14855        if (stagedDir != null) {
14856            origin = OriginInfo.fromStagedFile(stagedDir);
14857        } else {
14858            origin = OriginInfo.fromStagedContainer(stagedCid);
14859        }
14860
14861        final Message msg = mHandler.obtainMessage(INIT_COPY);
14862        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14863                sessionParams.installReason);
14864        final InstallParams params = new InstallParams(origin, null, observer,
14865                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14866                verificationInfo, user, sessionParams.abiOverride,
14867                sessionParams.grantedRuntimePermissions, certificates, installReason);
14868        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14869        msg.obj = params;
14870
14871        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14872                System.identityHashCode(msg.obj));
14873        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14874                System.identityHashCode(msg.obj));
14875
14876        mHandler.sendMessage(msg);
14877    }
14878
14879    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14880            int userId) {
14881        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14882        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14883                false /*startReceiver*/, pkgSetting.appId, userId);
14884
14885        // Send a session commit broadcast
14886        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14887        info.installReason = pkgSetting.getInstallReason(userId);
14888        info.appPackageName = packageName;
14889        sendSessionCommitBroadcast(info, userId);
14890    }
14891
14892    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14893            boolean includeStopped, int appId, int... userIds) {
14894        if (ArrayUtils.isEmpty(userIds)) {
14895            return;
14896        }
14897        Bundle extras = new Bundle(1);
14898        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14899        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14900
14901        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14902                packageName, extras, 0, null, null, userIds);
14903        if (sendBootCompleted) {
14904            mHandler.post(() -> {
14905                        for (int userId : userIds) {
14906                            sendBootCompletedBroadcastToSystemApp(
14907                                    packageName, includeStopped, userId);
14908                        }
14909                    }
14910            );
14911        }
14912    }
14913
14914    /**
14915     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14916     * automatically without needing an explicit launch.
14917     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14918     */
14919    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14920            int userId) {
14921        // If user is not running, the app didn't miss any broadcast
14922        if (!mUserManagerInternal.isUserRunning(userId)) {
14923            return;
14924        }
14925        final IActivityManager am = ActivityManager.getService();
14926        try {
14927            // Deliver LOCKED_BOOT_COMPLETED first
14928            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14929                    .setPackage(packageName);
14930            if (includeStopped) {
14931                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14932            }
14933            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14934            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14935                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14936
14937            // Deliver BOOT_COMPLETED only if user is unlocked
14938            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14939                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14940                if (includeStopped) {
14941                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14942                }
14943                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14944                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14945            }
14946        } catch (RemoteException e) {
14947            throw e.rethrowFromSystemServer();
14948        }
14949    }
14950
14951    @Override
14952    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14953            int userId) {
14954        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14955        PackageSetting pkgSetting;
14956        final int callingUid = Binder.getCallingUid();
14957        enforceCrossUserPermission(callingUid, userId,
14958                true /* requireFullPermission */, true /* checkShell */,
14959                "setApplicationHiddenSetting for user " + userId);
14960
14961        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14962            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14963            return false;
14964        }
14965
14966        long callingId = Binder.clearCallingIdentity();
14967        try {
14968            boolean sendAdded = false;
14969            boolean sendRemoved = false;
14970            // writer
14971            synchronized (mPackages) {
14972                pkgSetting = mSettings.mPackages.get(packageName);
14973                if (pkgSetting == null) {
14974                    return false;
14975                }
14976                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14977                    return false;
14978                }
14979                // Do not allow "android" is being disabled
14980                if ("android".equals(packageName)) {
14981                    Slog.w(TAG, "Cannot hide package: android");
14982                    return false;
14983                }
14984                // Cannot hide static shared libs as they are considered
14985                // a part of the using app (emulating static linking). Also
14986                // static libs are installed always on internal storage.
14987                PackageParser.Package pkg = mPackages.get(packageName);
14988                if (pkg != null && pkg.staticSharedLibName != null) {
14989                    Slog.w(TAG, "Cannot hide package: " + packageName
14990                            + " providing static shared library: "
14991                            + pkg.staticSharedLibName);
14992                    return false;
14993                }
14994                // Only allow protected packages to hide themselves.
14995                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14996                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14997                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14998                    return false;
14999                }
15000
15001                if (pkgSetting.getHidden(userId) != hidden) {
15002                    pkgSetting.setHidden(hidden, userId);
15003                    mSettings.writePackageRestrictionsLPr(userId);
15004                    if (hidden) {
15005                        sendRemoved = true;
15006                    } else {
15007                        sendAdded = true;
15008                    }
15009                }
15010            }
15011            if (sendAdded) {
15012                sendPackageAddedForUser(packageName, pkgSetting, userId);
15013                return true;
15014            }
15015            if (sendRemoved) {
15016                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
15017                        "hiding pkg");
15018                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
15019                return true;
15020            }
15021        } finally {
15022            Binder.restoreCallingIdentity(callingId);
15023        }
15024        return false;
15025    }
15026
15027    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
15028            int userId) {
15029        final PackageRemovedInfo info = new PackageRemovedInfo(this);
15030        info.removedPackage = packageName;
15031        info.installerPackageName = pkgSetting.installerPackageName;
15032        info.removedUsers = new int[] {userId};
15033        info.broadcastUsers = new int[] {userId};
15034        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
15035        info.sendPackageRemovedBroadcasts(true /*killApp*/);
15036    }
15037
15038    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
15039        if (pkgList.length > 0) {
15040            Bundle extras = new Bundle(1);
15041            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15042
15043            sendPackageBroadcast(
15044                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
15045                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
15046                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
15047                    new int[] {userId});
15048        }
15049    }
15050
15051    /**
15052     * Returns true if application is not found or there was an error. Otherwise it returns
15053     * the hidden state of the package for the given user.
15054     */
15055    @Override
15056    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
15057        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15058        final int callingUid = Binder.getCallingUid();
15059        enforceCrossUserPermission(callingUid, userId,
15060                true /* requireFullPermission */, false /* checkShell */,
15061                "getApplicationHidden for user " + userId);
15062        PackageSetting ps;
15063        long callingId = Binder.clearCallingIdentity();
15064        try {
15065            // writer
15066            synchronized (mPackages) {
15067                ps = mSettings.mPackages.get(packageName);
15068                if (ps == null) {
15069                    return true;
15070                }
15071                if (filterAppAccessLPr(ps, callingUid, userId)) {
15072                    return true;
15073                }
15074                return ps.getHidden(userId);
15075            }
15076        } finally {
15077            Binder.restoreCallingIdentity(callingId);
15078        }
15079    }
15080
15081    /**
15082     * @hide
15083     */
15084    @Override
15085    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
15086            int installReason) {
15087        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
15088                null);
15089        PackageSetting pkgSetting;
15090        final int callingUid = Binder.getCallingUid();
15091        enforceCrossUserPermission(callingUid, userId,
15092                true /* requireFullPermission */, true /* checkShell */,
15093                "installExistingPackage for user " + userId);
15094        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
15095            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
15096        }
15097
15098        long callingId = Binder.clearCallingIdentity();
15099        try {
15100            boolean installed = false;
15101            final boolean instantApp =
15102                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15103            final boolean fullApp =
15104                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
15105
15106            // writer
15107            synchronized (mPackages) {
15108                pkgSetting = mSettings.mPackages.get(packageName);
15109                if (pkgSetting == null) {
15110                    return PackageManager.INSTALL_FAILED_INVALID_URI;
15111                }
15112                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15113                    // only allow the existing package to be used if it's installed as a full
15114                    // application for at least one user
15115                    boolean installAllowed = false;
15116                    for (int checkUserId : sUserManager.getUserIds()) {
15117                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15118                        if (installAllowed) {
15119                            break;
15120                        }
15121                    }
15122                    if (!installAllowed) {
15123                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15124                    }
15125                }
15126                if (!pkgSetting.getInstalled(userId)) {
15127                    pkgSetting.setInstalled(true, userId);
15128                    pkgSetting.setHidden(false, userId);
15129                    pkgSetting.setInstallReason(installReason, userId);
15130                    mSettings.writePackageRestrictionsLPr(userId);
15131                    mSettings.writeKernelMappingLPr(pkgSetting);
15132                    installed = true;
15133                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15134                    // upgrade app from instant to full; we don't allow app downgrade
15135                    installed = true;
15136                }
15137                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15138            }
15139
15140            if (installed) {
15141                if (pkgSetting.pkg != null) {
15142                    synchronized (mInstallLock) {
15143                        // We don't need to freeze for a brand new install
15144                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15145                    }
15146                }
15147                sendPackageAddedForUser(packageName, pkgSetting, userId);
15148                synchronized (mPackages) {
15149                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15150                }
15151            }
15152        } finally {
15153            Binder.restoreCallingIdentity(callingId);
15154        }
15155
15156        return PackageManager.INSTALL_SUCCEEDED;
15157    }
15158
15159    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15160            boolean instantApp, boolean fullApp) {
15161        // no state specified; do nothing
15162        if (!instantApp && !fullApp) {
15163            return;
15164        }
15165        if (userId != UserHandle.USER_ALL) {
15166            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15167                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15168            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15169                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15170            }
15171        } else {
15172            for (int currentUserId : sUserManager.getUserIds()) {
15173                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15174                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15175                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15176                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15177                }
15178            }
15179        }
15180    }
15181
15182    boolean isUserRestricted(int userId, String restrictionKey) {
15183        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15184        if (restrictions.getBoolean(restrictionKey, false)) {
15185            Log.w(TAG, "User is restricted: " + restrictionKey);
15186            return true;
15187        }
15188        return false;
15189    }
15190
15191    @Override
15192    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15193            int userId) {
15194        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15195        final int callingUid = Binder.getCallingUid();
15196        enforceCrossUserPermission(callingUid, userId,
15197                true /* requireFullPermission */, true /* checkShell */,
15198                "setPackagesSuspended for user " + userId);
15199
15200        if (ArrayUtils.isEmpty(packageNames)) {
15201            return packageNames;
15202        }
15203
15204        // List of package names for whom the suspended state has changed.
15205        List<String> changedPackages = new ArrayList<>(packageNames.length);
15206        // List of package names for whom the suspended state is not set as requested in this
15207        // method.
15208        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15209        long callingId = Binder.clearCallingIdentity();
15210        try {
15211            for (int i = 0; i < packageNames.length; i++) {
15212                String packageName = packageNames[i];
15213                boolean changed = false;
15214                final int appId;
15215                synchronized (mPackages) {
15216                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15217                    if (pkgSetting == null
15218                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15219                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15220                                + "\". Skipping suspending/un-suspending.");
15221                        unactionedPackages.add(packageName);
15222                        continue;
15223                    }
15224                    appId = pkgSetting.appId;
15225                    if (pkgSetting.getSuspended(userId) != suspended) {
15226                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15227                            unactionedPackages.add(packageName);
15228                            continue;
15229                        }
15230                        pkgSetting.setSuspended(suspended, userId);
15231                        mSettings.writePackageRestrictionsLPr(userId);
15232                        changed = true;
15233                        changedPackages.add(packageName);
15234                    }
15235                }
15236
15237                if (changed && suspended) {
15238                    killApplication(packageName, UserHandle.getUid(userId, appId),
15239                            "suspending package");
15240                }
15241            }
15242        } finally {
15243            Binder.restoreCallingIdentity(callingId);
15244        }
15245
15246        if (!changedPackages.isEmpty()) {
15247            sendPackagesSuspendedForUser(changedPackages.toArray(
15248                    new String[changedPackages.size()]), userId, suspended);
15249        }
15250
15251        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15252    }
15253
15254    @Override
15255    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15256        final int callingUid = Binder.getCallingUid();
15257        enforceCrossUserPermission(callingUid, userId,
15258                true /* requireFullPermission */, false /* checkShell */,
15259                "isPackageSuspendedForUser for user " + userId);
15260        synchronized (mPackages) {
15261            final PackageSetting ps = mSettings.mPackages.get(packageName);
15262            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15263                throw new IllegalArgumentException("Unknown target package: " + packageName);
15264            }
15265            return ps.getSuspended(userId);
15266        }
15267    }
15268
15269    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15270        if (isPackageDeviceAdmin(packageName, userId)) {
15271            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15272                    + "\": has an active device admin");
15273            return false;
15274        }
15275
15276        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15277        if (packageName.equals(activeLauncherPackageName)) {
15278            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15279                    + "\": contains the active launcher");
15280            return false;
15281        }
15282
15283        if (packageName.equals(mRequiredInstallerPackage)) {
15284            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15285                    + "\": required for package installation");
15286            return false;
15287        }
15288
15289        if (packageName.equals(mRequiredUninstallerPackage)) {
15290            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15291                    + "\": required for package uninstallation");
15292            return false;
15293        }
15294
15295        if (packageName.equals(mRequiredVerifierPackage)) {
15296            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15297                    + "\": required for package verification");
15298            return false;
15299        }
15300
15301        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15302            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15303                    + "\": is the default dialer");
15304            return false;
15305        }
15306
15307        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15308            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15309                    + "\": protected package");
15310            return false;
15311        }
15312
15313        // Cannot suspend static shared libs as they are considered
15314        // a part of the using app (emulating static linking). Also
15315        // static libs are installed always on internal storage.
15316        PackageParser.Package pkg = mPackages.get(packageName);
15317        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15318            Slog.w(TAG, "Cannot suspend package: " + packageName
15319                    + " providing static shared library: "
15320                    + pkg.staticSharedLibName);
15321            return false;
15322        }
15323
15324        return true;
15325    }
15326
15327    private String getActiveLauncherPackageName(int userId) {
15328        Intent intent = new Intent(Intent.ACTION_MAIN);
15329        intent.addCategory(Intent.CATEGORY_HOME);
15330        ResolveInfo resolveInfo = resolveIntent(
15331                intent,
15332                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15333                PackageManager.MATCH_DEFAULT_ONLY,
15334                userId);
15335
15336        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15337    }
15338
15339    private String getDefaultDialerPackageName(int userId) {
15340        synchronized (mPackages) {
15341            return mSettings.getDefaultDialerPackageNameLPw(userId);
15342        }
15343    }
15344
15345    @Override
15346    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15347        mContext.enforceCallingOrSelfPermission(
15348                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15349                "Only package verification agents can verify applications");
15350
15351        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15352        final PackageVerificationResponse response = new PackageVerificationResponse(
15353                verificationCode, Binder.getCallingUid());
15354        msg.arg1 = id;
15355        msg.obj = response;
15356        mHandler.sendMessage(msg);
15357    }
15358
15359    @Override
15360    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15361            long millisecondsToDelay) {
15362        mContext.enforceCallingOrSelfPermission(
15363                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15364                "Only package verification agents can extend verification timeouts");
15365
15366        final PackageVerificationState state = mPendingVerification.get(id);
15367        final PackageVerificationResponse response = new PackageVerificationResponse(
15368                verificationCodeAtTimeout, Binder.getCallingUid());
15369
15370        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15371            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15372        }
15373        if (millisecondsToDelay < 0) {
15374            millisecondsToDelay = 0;
15375        }
15376        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15377                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15378            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15379        }
15380
15381        if ((state != null) && !state.timeoutExtended()) {
15382            state.extendTimeout();
15383
15384            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15385            msg.arg1 = id;
15386            msg.obj = response;
15387            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15388        }
15389    }
15390
15391    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15392            int verificationCode, UserHandle user) {
15393        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15394        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15395        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15396        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15397        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15398
15399        mContext.sendBroadcastAsUser(intent, user,
15400                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15401    }
15402
15403    private ComponentName matchComponentForVerifier(String packageName,
15404            List<ResolveInfo> receivers) {
15405        ActivityInfo targetReceiver = null;
15406
15407        final int NR = receivers.size();
15408        for (int i = 0; i < NR; i++) {
15409            final ResolveInfo info = receivers.get(i);
15410            if (info.activityInfo == null) {
15411                continue;
15412            }
15413
15414            if (packageName.equals(info.activityInfo.packageName)) {
15415                targetReceiver = info.activityInfo;
15416                break;
15417            }
15418        }
15419
15420        if (targetReceiver == null) {
15421            return null;
15422        }
15423
15424        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15425    }
15426
15427    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15428            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15429        if (pkgInfo.verifiers.length == 0) {
15430            return null;
15431        }
15432
15433        final int N = pkgInfo.verifiers.length;
15434        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15435        for (int i = 0; i < N; i++) {
15436            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15437
15438            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15439                    receivers);
15440            if (comp == null) {
15441                continue;
15442            }
15443
15444            final int verifierUid = getUidForVerifier(verifierInfo);
15445            if (verifierUid == -1) {
15446                continue;
15447            }
15448
15449            if (DEBUG_VERIFY) {
15450                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15451                        + " with the correct signature");
15452            }
15453            sufficientVerifiers.add(comp);
15454            verificationState.addSufficientVerifier(verifierUid);
15455        }
15456
15457        return sufficientVerifiers;
15458    }
15459
15460    private int getUidForVerifier(VerifierInfo verifierInfo) {
15461        synchronized (mPackages) {
15462            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15463            if (pkg == null) {
15464                return -1;
15465            } else if (pkg.mSignatures.length != 1) {
15466                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15467                        + " has more than one signature; ignoring");
15468                return -1;
15469            }
15470
15471            /*
15472             * If the public key of the package's signature does not match
15473             * our expected public key, then this is a different package and
15474             * we should skip.
15475             */
15476
15477            final byte[] expectedPublicKey;
15478            try {
15479                final Signature verifierSig = pkg.mSignatures[0];
15480                final PublicKey publicKey = verifierSig.getPublicKey();
15481                expectedPublicKey = publicKey.getEncoded();
15482            } catch (CertificateException e) {
15483                return -1;
15484            }
15485
15486            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15487
15488            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15489                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15490                        + " does not have the expected public key; ignoring");
15491                return -1;
15492            }
15493
15494            return pkg.applicationInfo.uid;
15495        }
15496    }
15497
15498    @Override
15499    public void finishPackageInstall(int token, boolean didLaunch) {
15500        enforceSystemOrRoot("Only the system is allowed to finish installs");
15501
15502        if (DEBUG_INSTALL) {
15503            Slog.v(TAG, "BM finishing package install for " + token);
15504        }
15505        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15506
15507        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15508        mHandler.sendMessage(msg);
15509    }
15510
15511    /**
15512     * Get the verification agent timeout.  Used for both the APK verifier and the
15513     * intent filter verifier.
15514     *
15515     * @return verification timeout in milliseconds
15516     */
15517    private long getVerificationTimeout() {
15518        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15519                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15520                DEFAULT_VERIFICATION_TIMEOUT);
15521    }
15522
15523    /**
15524     * Get the default verification agent response code.
15525     *
15526     * @return default verification response code
15527     */
15528    private int getDefaultVerificationResponse(UserHandle user) {
15529        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15530            return PackageManager.VERIFICATION_REJECT;
15531        }
15532        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15533                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15534                DEFAULT_VERIFICATION_RESPONSE);
15535    }
15536
15537    /**
15538     * Check whether or not package verification has been enabled.
15539     *
15540     * @return true if verification should be performed
15541     */
15542    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15543        if (!DEFAULT_VERIFY_ENABLE) {
15544            return false;
15545        }
15546
15547        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15548
15549        // Check if installing from ADB
15550        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15551            // Do not run verification in a test harness environment
15552            if (ActivityManager.isRunningInTestHarness()) {
15553                return false;
15554            }
15555            if (ensureVerifyAppsEnabled) {
15556                return true;
15557            }
15558            // Check if the developer does not want package verification for ADB installs
15559            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15560                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15561                return false;
15562            }
15563        } else {
15564            // only when not installed from ADB, skip verification for instant apps when
15565            // the installer and verifier are the same.
15566            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15567                if (mInstantAppInstallerActivity != null
15568                        && mInstantAppInstallerActivity.packageName.equals(
15569                                mRequiredVerifierPackage)) {
15570                    try {
15571                        mContext.getSystemService(AppOpsManager.class)
15572                                .checkPackage(installerUid, mRequiredVerifierPackage);
15573                        if (DEBUG_VERIFY) {
15574                            Slog.i(TAG, "disable verification for instant app");
15575                        }
15576                        return false;
15577                    } catch (SecurityException ignore) { }
15578                }
15579            }
15580        }
15581
15582        if (ensureVerifyAppsEnabled) {
15583            return true;
15584        }
15585
15586        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15587                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15588    }
15589
15590    @Override
15591    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15592            throws RemoteException {
15593        mContext.enforceCallingOrSelfPermission(
15594                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15595                "Only intentfilter verification agents can verify applications");
15596
15597        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15598        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15599                Binder.getCallingUid(), verificationCode, failedDomains);
15600        msg.arg1 = id;
15601        msg.obj = response;
15602        mHandler.sendMessage(msg);
15603    }
15604
15605    @Override
15606    public int getIntentVerificationStatus(String packageName, int userId) {
15607        final int callingUid = Binder.getCallingUid();
15608        if (UserHandle.getUserId(callingUid) != userId) {
15609            mContext.enforceCallingOrSelfPermission(
15610                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15611                    "getIntentVerificationStatus" + userId);
15612        }
15613        if (getInstantAppPackageName(callingUid) != null) {
15614            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15615        }
15616        synchronized (mPackages) {
15617            final PackageSetting ps = mSettings.mPackages.get(packageName);
15618            if (ps == null
15619                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15620                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15621            }
15622            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15623        }
15624    }
15625
15626    @Override
15627    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15628        mContext.enforceCallingOrSelfPermission(
15629                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15630
15631        boolean result = false;
15632        synchronized (mPackages) {
15633            final PackageSetting ps = mSettings.mPackages.get(packageName);
15634            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15635                return false;
15636            }
15637            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15638        }
15639        if (result) {
15640            scheduleWritePackageRestrictionsLocked(userId);
15641        }
15642        return result;
15643    }
15644
15645    @Override
15646    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15647            String packageName) {
15648        final int callingUid = Binder.getCallingUid();
15649        if (getInstantAppPackageName(callingUid) != null) {
15650            return ParceledListSlice.emptyList();
15651        }
15652        synchronized (mPackages) {
15653            final PackageSetting ps = mSettings.mPackages.get(packageName);
15654            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15655                return ParceledListSlice.emptyList();
15656            }
15657            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15658        }
15659    }
15660
15661    @Override
15662    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15663        if (TextUtils.isEmpty(packageName)) {
15664            return ParceledListSlice.emptyList();
15665        }
15666        final int callingUid = Binder.getCallingUid();
15667        final int callingUserId = UserHandle.getUserId(callingUid);
15668        synchronized (mPackages) {
15669            PackageParser.Package pkg = mPackages.get(packageName);
15670            if (pkg == null || pkg.activities == null) {
15671                return ParceledListSlice.emptyList();
15672            }
15673            if (pkg.mExtras == null) {
15674                return ParceledListSlice.emptyList();
15675            }
15676            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15677            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15678                return ParceledListSlice.emptyList();
15679            }
15680            final int count = pkg.activities.size();
15681            ArrayList<IntentFilter> result = new ArrayList<>();
15682            for (int n=0; n<count; n++) {
15683                PackageParser.Activity activity = pkg.activities.get(n);
15684                if (activity.intents != null && activity.intents.size() > 0) {
15685                    result.addAll(activity.intents);
15686                }
15687            }
15688            return new ParceledListSlice<>(result);
15689        }
15690    }
15691
15692    @Override
15693    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15694        mContext.enforceCallingOrSelfPermission(
15695                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15696        if (UserHandle.getCallingUserId() != userId) {
15697            mContext.enforceCallingOrSelfPermission(
15698                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15699        }
15700
15701        synchronized (mPackages) {
15702            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15703            if (packageName != null) {
15704                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15705                        packageName, userId);
15706            }
15707            return result;
15708        }
15709    }
15710
15711    @Override
15712    public String getDefaultBrowserPackageName(int userId) {
15713        if (UserHandle.getCallingUserId() != userId) {
15714            mContext.enforceCallingOrSelfPermission(
15715                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15716        }
15717        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15718            return null;
15719        }
15720        synchronized (mPackages) {
15721            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15722        }
15723    }
15724
15725    /**
15726     * Get the "allow unknown sources" setting.
15727     *
15728     * @return the current "allow unknown sources" setting
15729     */
15730    private int getUnknownSourcesSettings() {
15731        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15732                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15733                -1);
15734    }
15735
15736    @Override
15737    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15738        final int callingUid = Binder.getCallingUid();
15739        if (getInstantAppPackageName(callingUid) != null) {
15740            return;
15741        }
15742        // writer
15743        synchronized (mPackages) {
15744            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15745            if (targetPackageSetting == null
15746                    || filterAppAccessLPr(
15747                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15748                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15749            }
15750
15751            PackageSetting installerPackageSetting;
15752            if (installerPackageName != null) {
15753                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15754                if (installerPackageSetting == null) {
15755                    throw new IllegalArgumentException("Unknown installer package: "
15756                            + installerPackageName);
15757                }
15758            } else {
15759                installerPackageSetting = null;
15760            }
15761
15762            Signature[] callerSignature;
15763            Object obj = mSettings.getUserIdLPr(callingUid);
15764            if (obj != null) {
15765                if (obj instanceof SharedUserSetting) {
15766                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15767                } else if (obj instanceof PackageSetting) {
15768                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15769                } else {
15770                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15771                }
15772            } else {
15773                throw new SecurityException("Unknown calling UID: " + callingUid);
15774            }
15775
15776            // Verify: can't set installerPackageName to a package that is
15777            // not signed with the same cert as the caller.
15778            if (installerPackageSetting != null) {
15779                if (compareSignatures(callerSignature,
15780                        installerPackageSetting.signatures.mSignatures)
15781                        != PackageManager.SIGNATURE_MATCH) {
15782                    throw new SecurityException(
15783                            "Caller does not have same cert as new installer package "
15784                            + installerPackageName);
15785                }
15786            }
15787
15788            // Verify: if target already has an installer package, it must
15789            // be signed with the same cert as the caller.
15790            if (targetPackageSetting.installerPackageName != null) {
15791                PackageSetting setting = mSettings.mPackages.get(
15792                        targetPackageSetting.installerPackageName);
15793                // If the currently set package isn't valid, then it's always
15794                // okay to change it.
15795                if (setting != null) {
15796                    if (compareSignatures(callerSignature,
15797                            setting.signatures.mSignatures)
15798                            != PackageManager.SIGNATURE_MATCH) {
15799                        throw new SecurityException(
15800                                "Caller does not have same cert as old installer package "
15801                                + targetPackageSetting.installerPackageName);
15802                    }
15803                }
15804            }
15805
15806            // Okay!
15807            targetPackageSetting.installerPackageName = installerPackageName;
15808            if (installerPackageName != null) {
15809                mSettings.mInstallerPackages.add(installerPackageName);
15810            }
15811            scheduleWriteSettingsLocked();
15812        }
15813    }
15814
15815    @Override
15816    public void setApplicationCategoryHint(String packageName, int categoryHint,
15817            String callerPackageName) {
15818        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15819            throw new SecurityException("Instant applications don't have access to this method");
15820        }
15821        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15822                callerPackageName);
15823        synchronized (mPackages) {
15824            PackageSetting ps = mSettings.mPackages.get(packageName);
15825            if (ps == null) {
15826                throw new IllegalArgumentException("Unknown target package " + packageName);
15827            }
15828            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15829                throw new IllegalArgumentException("Unknown target package " + packageName);
15830            }
15831            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15832                throw new IllegalArgumentException("Calling package " + callerPackageName
15833                        + " is not installer for " + packageName);
15834            }
15835
15836            if (ps.categoryHint != categoryHint) {
15837                ps.categoryHint = categoryHint;
15838                scheduleWriteSettingsLocked();
15839            }
15840        }
15841    }
15842
15843    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15844        // Queue up an async operation since the package installation may take a little while.
15845        mHandler.post(new Runnable() {
15846            public void run() {
15847                mHandler.removeCallbacks(this);
15848                 // Result object to be returned
15849                PackageInstalledInfo res = new PackageInstalledInfo();
15850                res.setReturnCode(currentStatus);
15851                res.uid = -1;
15852                res.pkg = null;
15853                res.removedInfo = null;
15854                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15855                    args.doPreInstall(res.returnCode);
15856                    synchronized (mInstallLock) {
15857                        installPackageTracedLI(args, res);
15858                    }
15859                    args.doPostInstall(res.returnCode, res.uid);
15860                }
15861
15862                // A restore should be performed at this point if (a) the install
15863                // succeeded, (b) the operation is not an update, and (c) the new
15864                // package has not opted out of backup participation.
15865                final boolean update = res.removedInfo != null
15866                        && res.removedInfo.removedPackage != null;
15867                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15868                boolean doRestore = !update
15869                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15870
15871                // Set up the post-install work request bookkeeping.  This will be used
15872                // and cleaned up by the post-install event handling regardless of whether
15873                // there's a restore pass performed.  Token values are >= 1.
15874                int token;
15875                if (mNextInstallToken < 0) mNextInstallToken = 1;
15876                token = mNextInstallToken++;
15877
15878                PostInstallData data = new PostInstallData(args, res);
15879                mRunningInstalls.put(token, data);
15880                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15881
15882                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15883                    // Pass responsibility to the Backup Manager.  It will perform a
15884                    // restore if appropriate, then pass responsibility back to the
15885                    // Package Manager to run the post-install observer callbacks
15886                    // and broadcasts.
15887                    IBackupManager bm = IBackupManager.Stub.asInterface(
15888                            ServiceManager.getService(Context.BACKUP_SERVICE));
15889                    if (bm != null) {
15890                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15891                                + " to BM for possible restore");
15892                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15893                        try {
15894                            // TODO: http://b/22388012
15895                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15896                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15897                            } else {
15898                                doRestore = false;
15899                            }
15900                        } catch (RemoteException e) {
15901                            // can't happen; the backup manager is local
15902                        } catch (Exception e) {
15903                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15904                            doRestore = false;
15905                        }
15906                    } else {
15907                        Slog.e(TAG, "Backup Manager not found!");
15908                        doRestore = false;
15909                    }
15910                }
15911
15912                if (!doRestore) {
15913                    // No restore possible, or the Backup Manager was mysteriously not
15914                    // available -- just fire the post-install work request directly.
15915                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15916
15917                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15918
15919                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15920                    mHandler.sendMessage(msg);
15921                }
15922            }
15923        });
15924    }
15925
15926    /**
15927     * Callback from PackageSettings whenever an app is first transitioned out of the
15928     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15929     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15930     * here whether the app is the target of an ongoing install, and only send the
15931     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15932     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15933     * handling.
15934     */
15935    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15936        // Serialize this with the rest of the install-process message chain.  In the
15937        // restore-at-install case, this Runnable will necessarily run before the
15938        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15939        // are coherent.  In the non-restore case, the app has already completed install
15940        // and been launched through some other means, so it is not in a problematic
15941        // state for observers to see the FIRST_LAUNCH signal.
15942        mHandler.post(new Runnable() {
15943            @Override
15944            public void run() {
15945                for (int i = 0; i < mRunningInstalls.size(); i++) {
15946                    final PostInstallData data = mRunningInstalls.valueAt(i);
15947                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15948                        continue;
15949                    }
15950                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15951                        // right package; but is it for the right user?
15952                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15953                            if (userId == data.res.newUsers[uIndex]) {
15954                                if (DEBUG_BACKUP) {
15955                                    Slog.i(TAG, "Package " + pkgName
15956                                            + " being restored so deferring FIRST_LAUNCH");
15957                                }
15958                                return;
15959                            }
15960                        }
15961                    }
15962                }
15963                // didn't find it, so not being restored
15964                if (DEBUG_BACKUP) {
15965                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15966                }
15967                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15968            }
15969        });
15970    }
15971
15972    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15973        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15974                installerPkg, null, userIds);
15975    }
15976
15977    private abstract class HandlerParams {
15978        private static final int MAX_RETRIES = 4;
15979
15980        /**
15981         * Number of times startCopy() has been attempted and had a non-fatal
15982         * error.
15983         */
15984        private int mRetries = 0;
15985
15986        /** User handle for the user requesting the information or installation. */
15987        private final UserHandle mUser;
15988        String traceMethod;
15989        int traceCookie;
15990
15991        HandlerParams(UserHandle user) {
15992            mUser = user;
15993        }
15994
15995        UserHandle getUser() {
15996            return mUser;
15997        }
15998
15999        HandlerParams setTraceMethod(String traceMethod) {
16000            this.traceMethod = traceMethod;
16001            return this;
16002        }
16003
16004        HandlerParams setTraceCookie(int traceCookie) {
16005            this.traceCookie = traceCookie;
16006            return this;
16007        }
16008
16009        final boolean startCopy() {
16010            boolean res;
16011            try {
16012                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
16013
16014                if (++mRetries > MAX_RETRIES) {
16015                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
16016                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
16017                    handleServiceError();
16018                    return false;
16019                } else {
16020                    handleStartCopy();
16021                    res = true;
16022                }
16023            } catch (RemoteException e) {
16024                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
16025                mHandler.sendEmptyMessage(MCS_RECONNECT);
16026                res = false;
16027            }
16028            handleReturnCode();
16029            return res;
16030        }
16031
16032        final void serviceError() {
16033            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
16034            handleServiceError();
16035            handleReturnCode();
16036        }
16037
16038        abstract void handleStartCopy() throws RemoteException;
16039        abstract void handleServiceError();
16040        abstract void handleReturnCode();
16041    }
16042
16043    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
16044        for (File path : paths) {
16045            try {
16046                mcs.clearDirectory(path.getAbsolutePath());
16047            } catch (RemoteException e) {
16048            }
16049        }
16050    }
16051
16052    static class OriginInfo {
16053        /**
16054         * Location where install is coming from, before it has been
16055         * copied/renamed into place. This could be a single monolithic APK
16056         * file, or a cluster directory. This location may be untrusted.
16057         */
16058        final File file;
16059        final String cid;
16060
16061        /**
16062         * Flag indicating that {@link #file} or {@link #cid} has already been
16063         * staged, meaning downstream users don't need to defensively copy the
16064         * contents.
16065         */
16066        final boolean staged;
16067
16068        /**
16069         * Flag indicating that {@link #file} or {@link #cid} is an already
16070         * installed app that is being moved.
16071         */
16072        final boolean existing;
16073
16074        final String resolvedPath;
16075        final File resolvedFile;
16076
16077        static OriginInfo fromNothing() {
16078            return new OriginInfo(null, null, false, false);
16079        }
16080
16081        static OriginInfo fromUntrustedFile(File file) {
16082            return new OriginInfo(file, null, false, false);
16083        }
16084
16085        static OriginInfo fromExistingFile(File file) {
16086            return new OriginInfo(file, null, false, true);
16087        }
16088
16089        static OriginInfo fromStagedFile(File file) {
16090            return new OriginInfo(file, null, true, false);
16091        }
16092
16093        static OriginInfo fromStagedContainer(String cid) {
16094            return new OriginInfo(null, cid, true, false);
16095        }
16096
16097        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
16098            this.file = file;
16099            this.cid = cid;
16100            this.staged = staged;
16101            this.existing = existing;
16102
16103            if (cid != null) {
16104                resolvedPath = PackageHelper.getSdDir(cid);
16105                resolvedFile = new File(resolvedPath);
16106            } else if (file != null) {
16107                resolvedPath = file.getAbsolutePath();
16108                resolvedFile = file;
16109            } else {
16110                resolvedPath = null;
16111                resolvedFile = null;
16112            }
16113        }
16114    }
16115
16116    static class MoveInfo {
16117        final int moveId;
16118        final String fromUuid;
16119        final String toUuid;
16120        final String packageName;
16121        final String dataAppName;
16122        final int appId;
16123        final String seinfo;
16124        final int targetSdkVersion;
16125
16126        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16127                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16128            this.moveId = moveId;
16129            this.fromUuid = fromUuid;
16130            this.toUuid = toUuid;
16131            this.packageName = packageName;
16132            this.dataAppName = dataAppName;
16133            this.appId = appId;
16134            this.seinfo = seinfo;
16135            this.targetSdkVersion = targetSdkVersion;
16136        }
16137    }
16138
16139    static class VerificationInfo {
16140        /** A constant used to indicate that a uid value is not present. */
16141        public static final int NO_UID = -1;
16142
16143        /** URI referencing where the package was downloaded from. */
16144        final Uri originatingUri;
16145
16146        /** HTTP referrer URI associated with the originatingURI. */
16147        final Uri referrer;
16148
16149        /** UID of the application that the install request originated from. */
16150        final int originatingUid;
16151
16152        /** UID of application requesting the install */
16153        final int installerUid;
16154
16155        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16156            this.originatingUri = originatingUri;
16157            this.referrer = referrer;
16158            this.originatingUid = originatingUid;
16159            this.installerUid = installerUid;
16160        }
16161    }
16162
16163    class InstallParams extends HandlerParams {
16164        final OriginInfo origin;
16165        final MoveInfo move;
16166        final IPackageInstallObserver2 observer;
16167        int installFlags;
16168        final String installerPackageName;
16169        final String volumeUuid;
16170        private InstallArgs mArgs;
16171        private int mRet;
16172        final String packageAbiOverride;
16173        final String[] grantedRuntimePermissions;
16174        final VerificationInfo verificationInfo;
16175        final Certificate[][] certificates;
16176        final int installReason;
16177
16178        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16179                int installFlags, String installerPackageName, String volumeUuid,
16180                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16181                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16182            super(user);
16183            this.origin = origin;
16184            this.move = move;
16185            this.observer = observer;
16186            this.installFlags = installFlags;
16187            this.installerPackageName = installerPackageName;
16188            this.volumeUuid = volumeUuid;
16189            this.verificationInfo = verificationInfo;
16190            this.packageAbiOverride = packageAbiOverride;
16191            this.grantedRuntimePermissions = grantedPermissions;
16192            this.certificates = certificates;
16193            this.installReason = installReason;
16194        }
16195
16196        @Override
16197        public String toString() {
16198            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16199                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16200        }
16201
16202        private int installLocationPolicy(PackageInfoLite pkgLite) {
16203            String packageName = pkgLite.packageName;
16204            int installLocation = pkgLite.installLocation;
16205            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16206            // reader
16207            synchronized (mPackages) {
16208                // Currently installed package which the new package is attempting to replace or
16209                // null if no such package is installed.
16210                PackageParser.Package installedPkg = mPackages.get(packageName);
16211                // Package which currently owns the data which the new package will own if installed.
16212                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16213                // will be null whereas dataOwnerPkg will contain information about the package
16214                // which was uninstalled while keeping its data.
16215                PackageParser.Package dataOwnerPkg = installedPkg;
16216                if (dataOwnerPkg  == null) {
16217                    PackageSetting ps = mSettings.mPackages.get(packageName);
16218                    if (ps != null) {
16219                        dataOwnerPkg = ps.pkg;
16220                    }
16221                }
16222
16223                if (dataOwnerPkg != null) {
16224                    // If installed, the package will get access to data left on the device by its
16225                    // predecessor. As a security measure, this is permited only if this is not a
16226                    // version downgrade or if the predecessor package is marked as debuggable and
16227                    // a downgrade is explicitly requested.
16228                    //
16229                    // On debuggable platform builds, downgrades are permitted even for
16230                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16231                    // not offer security guarantees and thus it's OK to disable some security
16232                    // mechanisms to make debugging/testing easier on those builds. However, even on
16233                    // debuggable builds downgrades of packages are permitted only if requested via
16234                    // installFlags. This is because we aim to keep the behavior of debuggable
16235                    // platform builds as close as possible to the behavior of non-debuggable
16236                    // platform builds.
16237                    final boolean downgradeRequested =
16238                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16239                    final boolean packageDebuggable =
16240                                (dataOwnerPkg.applicationInfo.flags
16241                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16242                    final boolean downgradePermitted =
16243                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16244                    if (!downgradePermitted) {
16245                        try {
16246                            checkDowngrade(dataOwnerPkg, pkgLite);
16247                        } catch (PackageManagerException e) {
16248                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16249                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16250                        }
16251                    }
16252                }
16253
16254                if (installedPkg != null) {
16255                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16256                        // Check for updated system application.
16257                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16258                            if (onSd) {
16259                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16260                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16261                            }
16262                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16263                        } else {
16264                            if (onSd) {
16265                                // Install flag overrides everything.
16266                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16267                            }
16268                            // If current upgrade specifies particular preference
16269                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16270                                // Application explicitly specified internal.
16271                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16272                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16273                                // App explictly prefers external. Let policy decide
16274                            } else {
16275                                // Prefer previous location
16276                                if (isExternal(installedPkg)) {
16277                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16278                                }
16279                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16280                            }
16281                        }
16282                    } else {
16283                        // Invalid install. Return error code
16284                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16285                    }
16286                }
16287            }
16288            // All the special cases have been taken care of.
16289            // Return result based on recommended install location.
16290            if (onSd) {
16291                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16292            }
16293            return pkgLite.recommendedInstallLocation;
16294        }
16295
16296        /*
16297         * Invoke remote method to get package information and install
16298         * location values. Override install location based on default
16299         * policy if needed and then create install arguments based
16300         * on the install location.
16301         */
16302        public void handleStartCopy() throws RemoteException {
16303            int ret = PackageManager.INSTALL_SUCCEEDED;
16304
16305            // If we're already staged, we've firmly committed to an install location
16306            if (origin.staged) {
16307                if (origin.file != null) {
16308                    installFlags |= PackageManager.INSTALL_INTERNAL;
16309                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16310                } else if (origin.cid != null) {
16311                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16312                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16313                } else {
16314                    throw new IllegalStateException("Invalid stage location");
16315                }
16316            }
16317
16318            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16319            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16320            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16321            PackageInfoLite pkgLite = null;
16322
16323            if (onInt && onSd) {
16324                // Check if both bits are set.
16325                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16326                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16327            } else if (onSd && ephemeral) {
16328                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16329                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16330            } else {
16331                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16332                        packageAbiOverride);
16333
16334                if (DEBUG_EPHEMERAL && ephemeral) {
16335                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16336                }
16337
16338                /*
16339                 * If we have too little free space, try to free cache
16340                 * before giving up.
16341                 */
16342                if (!origin.staged && pkgLite.recommendedInstallLocation
16343                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16344                    // TODO: focus freeing disk space on the target device
16345                    final StorageManager storage = StorageManager.from(mContext);
16346                    final long lowThreshold = storage.getStorageLowBytes(
16347                            Environment.getDataDirectory());
16348
16349                    final long sizeBytes = mContainerService.calculateInstalledSize(
16350                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16351
16352                    try {
16353                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16354                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16355                                installFlags, packageAbiOverride);
16356                    } catch (InstallerException e) {
16357                        Slog.w(TAG, "Failed to free cache", e);
16358                    }
16359
16360                    /*
16361                     * The cache free must have deleted the file we
16362                     * downloaded to install.
16363                     *
16364                     * TODO: fix the "freeCache" call to not delete
16365                     *       the file we care about.
16366                     */
16367                    if (pkgLite.recommendedInstallLocation
16368                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16369                        pkgLite.recommendedInstallLocation
16370                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16371                    }
16372                }
16373            }
16374
16375            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16376                int loc = pkgLite.recommendedInstallLocation;
16377                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16378                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16379                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16380                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16381                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16382                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16383                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16384                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16385                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16386                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16387                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16388                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16389                } else {
16390                    // Override with defaults if needed.
16391                    loc = installLocationPolicy(pkgLite);
16392                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16393                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16394                    } else if (!onSd && !onInt) {
16395                        // Override install location with flags
16396                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16397                            // Set the flag to install on external media.
16398                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16399                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16400                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16401                            if (DEBUG_EPHEMERAL) {
16402                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16403                            }
16404                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16405                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16406                                    |PackageManager.INSTALL_INTERNAL);
16407                        } else {
16408                            // Make sure the flag for installing on external
16409                            // media is unset
16410                            installFlags |= PackageManager.INSTALL_INTERNAL;
16411                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16412                        }
16413                    }
16414                }
16415            }
16416
16417            final InstallArgs args = createInstallArgs(this);
16418            mArgs = args;
16419
16420            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16421                // TODO: http://b/22976637
16422                // Apps installed for "all" users use the device owner to verify the app
16423                UserHandle verifierUser = getUser();
16424                if (verifierUser == UserHandle.ALL) {
16425                    verifierUser = UserHandle.SYSTEM;
16426                }
16427
16428                /*
16429                 * Determine if we have any installed package verifiers. If we
16430                 * do, then we'll defer to them to verify the packages.
16431                 */
16432                final int requiredUid = mRequiredVerifierPackage == null ? -1
16433                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16434                                verifierUser.getIdentifier());
16435                final int installerUid =
16436                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16437                if (!origin.existing && requiredUid != -1
16438                        && isVerificationEnabled(
16439                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16440                    final Intent verification = new Intent(
16441                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16442                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16443                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16444                            PACKAGE_MIME_TYPE);
16445                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16446
16447                    // Query all live verifiers based on current user state
16448                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16449                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16450                            false /*allowDynamicSplits*/);
16451
16452                    if (DEBUG_VERIFY) {
16453                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16454                                + verification.toString() + " with " + pkgLite.verifiers.length
16455                                + " optional verifiers");
16456                    }
16457
16458                    final int verificationId = mPendingVerificationToken++;
16459
16460                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16461
16462                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16463                            installerPackageName);
16464
16465                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16466                            installFlags);
16467
16468                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16469                            pkgLite.packageName);
16470
16471                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16472                            pkgLite.versionCode);
16473
16474                    if (verificationInfo != null) {
16475                        if (verificationInfo.originatingUri != null) {
16476                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16477                                    verificationInfo.originatingUri);
16478                        }
16479                        if (verificationInfo.referrer != null) {
16480                            verification.putExtra(Intent.EXTRA_REFERRER,
16481                                    verificationInfo.referrer);
16482                        }
16483                        if (verificationInfo.originatingUid >= 0) {
16484                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16485                                    verificationInfo.originatingUid);
16486                        }
16487                        if (verificationInfo.installerUid >= 0) {
16488                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16489                                    verificationInfo.installerUid);
16490                        }
16491                    }
16492
16493                    final PackageVerificationState verificationState = new PackageVerificationState(
16494                            requiredUid, args);
16495
16496                    mPendingVerification.append(verificationId, verificationState);
16497
16498                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16499                            receivers, verificationState);
16500
16501                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16502                    final long idleDuration = getVerificationTimeout();
16503
16504                    /*
16505                     * If any sufficient verifiers were listed in the package
16506                     * manifest, attempt to ask them.
16507                     */
16508                    if (sufficientVerifiers != null) {
16509                        final int N = sufficientVerifiers.size();
16510                        if (N == 0) {
16511                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16512                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16513                        } else {
16514                            for (int i = 0; i < N; i++) {
16515                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16516                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16517                                        verifierComponent.getPackageName(), idleDuration,
16518                                        verifierUser.getIdentifier(), false, "package verifier");
16519
16520                                final Intent sufficientIntent = new Intent(verification);
16521                                sufficientIntent.setComponent(verifierComponent);
16522                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16523                            }
16524                        }
16525                    }
16526
16527                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16528                            mRequiredVerifierPackage, receivers);
16529                    if (ret == PackageManager.INSTALL_SUCCEEDED
16530                            && mRequiredVerifierPackage != null) {
16531                        Trace.asyncTraceBegin(
16532                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16533                        /*
16534                         * Send the intent to the required verification agent,
16535                         * but only start the verification timeout after the
16536                         * target BroadcastReceivers have run.
16537                         */
16538                        verification.setComponent(requiredVerifierComponent);
16539                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16540                                mRequiredVerifierPackage, idleDuration,
16541                                verifierUser.getIdentifier(), false, "package verifier");
16542                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16543                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16544                                new BroadcastReceiver() {
16545                                    @Override
16546                                    public void onReceive(Context context, Intent intent) {
16547                                        final Message msg = mHandler
16548                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16549                                        msg.arg1 = verificationId;
16550                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16551                                    }
16552                                }, null, 0, null, null);
16553
16554                        /*
16555                         * We don't want the copy to proceed until verification
16556                         * succeeds, so null out this field.
16557                         */
16558                        mArgs = null;
16559                    }
16560                } else {
16561                    /*
16562                     * No package verification is enabled, so immediately start
16563                     * the remote call to initiate copy using temporary file.
16564                     */
16565                    ret = args.copyApk(mContainerService, true);
16566                }
16567            }
16568
16569            mRet = ret;
16570        }
16571
16572        @Override
16573        void handleReturnCode() {
16574            // If mArgs is null, then MCS couldn't be reached. When it
16575            // reconnects, it will try again to install. At that point, this
16576            // will succeed.
16577            if (mArgs != null) {
16578                processPendingInstall(mArgs, mRet);
16579            }
16580        }
16581
16582        @Override
16583        void handleServiceError() {
16584            mArgs = createInstallArgs(this);
16585            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16586        }
16587
16588        public boolean isForwardLocked() {
16589            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16590        }
16591    }
16592
16593    /**
16594     * Used during creation of InstallArgs
16595     *
16596     * @param installFlags package installation flags
16597     * @return true if should be installed on external storage
16598     */
16599    private static boolean installOnExternalAsec(int installFlags) {
16600        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16601            return false;
16602        }
16603        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16604            return true;
16605        }
16606        return false;
16607    }
16608
16609    /**
16610     * Used during creation of InstallArgs
16611     *
16612     * @param installFlags package installation flags
16613     * @return true if should be installed as forward locked
16614     */
16615    private static boolean installForwardLocked(int installFlags) {
16616        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16617    }
16618
16619    private InstallArgs createInstallArgs(InstallParams params) {
16620        if (params.move != null) {
16621            return new MoveInstallArgs(params);
16622        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16623            return new AsecInstallArgs(params);
16624        } else {
16625            return new FileInstallArgs(params);
16626        }
16627    }
16628
16629    /**
16630     * Create args that describe an existing installed package. Typically used
16631     * when cleaning up old installs, or used as a move source.
16632     */
16633    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16634            String resourcePath, String[] instructionSets) {
16635        final boolean isInAsec;
16636        if (installOnExternalAsec(installFlags)) {
16637            /* Apps on SD card are always in ASEC containers. */
16638            isInAsec = true;
16639        } else if (installForwardLocked(installFlags)
16640                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16641            /*
16642             * Forward-locked apps are only in ASEC containers if they're the
16643             * new style
16644             */
16645            isInAsec = true;
16646        } else {
16647            isInAsec = false;
16648        }
16649
16650        if (isInAsec) {
16651            return new AsecInstallArgs(codePath, instructionSets,
16652                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16653        } else {
16654            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16655        }
16656    }
16657
16658    static abstract class InstallArgs {
16659        /** @see InstallParams#origin */
16660        final OriginInfo origin;
16661        /** @see InstallParams#move */
16662        final MoveInfo move;
16663
16664        final IPackageInstallObserver2 observer;
16665        // Always refers to PackageManager flags only
16666        final int installFlags;
16667        final String installerPackageName;
16668        final String volumeUuid;
16669        final UserHandle user;
16670        final String abiOverride;
16671        final String[] installGrantPermissions;
16672        /** If non-null, drop an async trace when the install completes */
16673        final String traceMethod;
16674        final int traceCookie;
16675        final Certificate[][] certificates;
16676        final int installReason;
16677
16678        // The list of instruction sets supported by this app. This is currently
16679        // only used during the rmdex() phase to clean up resources. We can get rid of this
16680        // if we move dex files under the common app path.
16681        /* nullable */ String[] instructionSets;
16682
16683        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16684                int installFlags, String installerPackageName, String volumeUuid,
16685                UserHandle user, String[] instructionSets,
16686                String abiOverride, String[] installGrantPermissions,
16687                String traceMethod, int traceCookie, Certificate[][] certificates,
16688                int installReason) {
16689            this.origin = origin;
16690            this.move = move;
16691            this.installFlags = installFlags;
16692            this.observer = observer;
16693            this.installerPackageName = installerPackageName;
16694            this.volumeUuid = volumeUuid;
16695            this.user = user;
16696            this.instructionSets = instructionSets;
16697            this.abiOverride = abiOverride;
16698            this.installGrantPermissions = installGrantPermissions;
16699            this.traceMethod = traceMethod;
16700            this.traceCookie = traceCookie;
16701            this.certificates = certificates;
16702            this.installReason = installReason;
16703        }
16704
16705        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16706        abstract int doPreInstall(int status);
16707
16708        /**
16709         * Rename package into final resting place. All paths on the given
16710         * scanned package should be updated to reflect the rename.
16711         */
16712        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16713        abstract int doPostInstall(int status, int uid);
16714
16715        /** @see PackageSettingBase#codePathString */
16716        abstract String getCodePath();
16717        /** @see PackageSettingBase#resourcePathString */
16718        abstract String getResourcePath();
16719
16720        // Need installer lock especially for dex file removal.
16721        abstract void cleanUpResourcesLI();
16722        abstract boolean doPostDeleteLI(boolean delete);
16723
16724        /**
16725         * Called before the source arguments are copied. This is used mostly
16726         * for MoveParams when it needs to read the source file to put it in the
16727         * destination.
16728         */
16729        int doPreCopy() {
16730            return PackageManager.INSTALL_SUCCEEDED;
16731        }
16732
16733        /**
16734         * Called after the source arguments are copied. This is used mostly for
16735         * MoveParams when it needs to read the source file to put it in the
16736         * destination.
16737         */
16738        int doPostCopy(int uid) {
16739            return PackageManager.INSTALL_SUCCEEDED;
16740        }
16741
16742        protected boolean isFwdLocked() {
16743            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16744        }
16745
16746        protected boolean isExternalAsec() {
16747            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16748        }
16749
16750        protected boolean isEphemeral() {
16751            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16752        }
16753
16754        UserHandle getUser() {
16755            return user;
16756        }
16757    }
16758
16759    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16760        if (!allCodePaths.isEmpty()) {
16761            if (instructionSets == null) {
16762                throw new IllegalStateException("instructionSet == null");
16763            }
16764            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16765            for (String codePath : allCodePaths) {
16766                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16767                    try {
16768                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16769                    } catch (InstallerException ignored) {
16770                    }
16771                }
16772            }
16773        }
16774    }
16775
16776    /**
16777     * Logic to handle installation of non-ASEC applications, including copying
16778     * and renaming logic.
16779     */
16780    class FileInstallArgs extends InstallArgs {
16781        private File codeFile;
16782        private File resourceFile;
16783
16784        // Example topology:
16785        // /data/app/com.example/base.apk
16786        // /data/app/com.example/split_foo.apk
16787        // /data/app/com.example/lib/arm/libfoo.so
16788        // /data/app/com.example/lib/arm64/libfoo.so
16789        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16790
16791        /** New install */
16792        FileInstallArgs(InstallParams params) {
16793            super(params.origin, params.move, params.observer, params.installFlags,
16794                    params.installerPackageName, params.volumeUuid,
16795                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16796                    params.grantedRuntimePermissions,
16797                    params.traceMethod, params.traceCookie, params.certificates,
16798                    params.installReason);
16799            if (isFwdLocked()) {
16800                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16801            }
16802        }
16803
16804        /** Existing install */
16805        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16806            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16807                    null, null, null, 0, null /*certificates*/,
16808                    PackageManager.INSTALL_REASON_UNKNOWN);
16809            this.codeFile = (codePath != null) ? new File(codePath) : null;
16810            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16811        }
16812
16813        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16814            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16815            try {
16816                return doCopyApk(imcs, temp);
16817            } finally {
16818                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16819            }
16820        }
16821
16822        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16823            if (origin.staged) {
16824                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16825                codeFile = origin.file;
16826                resourceFile = origin.file;
16827                return PackageManager.INSTALL_SUCCEEDED;
16828            }
16829
16830            try {
16831                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16832                final File tempDir =
16833                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16834                codeFile = tempDir;
16835                resourceFile = tempDir;
16836            } catch (IOException e) {
16837                Slog.w(TAG, "Failed to create copy file: " + e);
16838                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16839            }
16840
16841            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16842                @Override
16843                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16844                    if (!FileUtils.isValidExtFilename(name)) {
16845                        throw new IllegalArgumentException("Invalid filename: " + name);
16846                    }
16847                    try {
16848                        final File file = new File(codeFile, name);
16849                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16850                                O_RDWR | O_CREAT, 0644);
16851                        Os.chmod(file.getAbsolutePath(), 0644);
16852                        return new ParcelFileDescriptor(fd);
16853                    } catch (ErrnoException e) {
16854                        throw new RemoteException("Failed to open: " + e.getMessage());
16855                    }
16856                }
16857            };
16858
16859            int ret = PackageManager.INSTALL_SUCCEEDED;
16860            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16861            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16862                Slog.e(TAG, "Failed to copy package");
16863                return ret;
16864            }
16865
16866            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16867            NativeLibraryHelper.Handle handle = null;
16868            try {
16869                handle = NativeLibraryHelper.Handle.create(codeFile);
16870                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16871                        abiOverride);
16872            } catch (IOException e) {
16873                Slog.e(TAG, "Copying native libraries failed", e);
16874                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16875            } finally {
16876                IoUtils.closeQuietly(handle);
16877            }
16878
16879            return ret;
16880        }
16881
16882        int doPreInstall(int status) {
16883            if (status != PackageManager.INSTALL_SUCCEEDED) {
16884                cleanUp();
16885            }
16886            return status;
16887        }
16888
16889        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16890            if (status != PackageManager.INSTALL_SUCCEEDED) {
16891                cleanUp();
16892                return false;
16893            }
16894
16895            final File targetDir = codeFile.getParentFile();
16896            final File beforeCodeFile = codeFile;
16897            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16898
16899            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16900            try {
16901                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16902            } catch (ErrnoException e) {
16903                Slog.w(TAG, "Failed to rename", e);
16904                return false;
16905            }
16906
16907            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16908                Slog.w(TAG, "Failed to restorecon");
16909                return false;
16910            }
16911
16912            // Reflect the rename internally
16913            codeFile = afterCodeFile;
16914            resourceFile = afterCodeFile;
16915
16916            // Reflect the rename in scanned details
16917            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16918            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16919                    afterCodeFile, pkg.baseCodePath));
16920            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16921                    afterCodeFile, pkg.splitCodePaths));
16922
16923            // Reflect the rename in app info
16924            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16925            pkg.setApplicationInfoCodePath(pkg.codePath);
16926            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16927            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16928            pkg.setApplicationInfoResourcePath(pkg.codePath);
16929            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16930            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16931
16932            return true;
16933        }
16934
16935        int doPostInstall(int status, int uid) {
16936            if (status != PackageManager.INSTALL_SUCCEEDED) {
16937                cleanUp();
16938            }
16939            return status;
16940        }
16941
16942        @Override
16943        String getCodePath() {
16944            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16945        }
16946
16947        @Override
16948        String getResourcePath() {
16949            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16950        }
16951
16952        private boolean cleanUp() {
16953            if (codeFile == null || !codeFile.exists()) {
16954                return false;
16955            }
16956
16957            removeCodePathLI(codeFile);
16958
16959            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16960                resourceFile.delete();
16961            }
16962
16963            return true;
16964        }
16965
16966        void cleanUpResourcesLI() {
16967            // Try enumerating all code paths before deleting
16968            List<String> allCodePaths = Collections.EMPTY_LIST;
16969            if (codeFile != null && codeFile.exists()) {
16970                try {
16971                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16972                    allCodePaths = pkg.getAllCodePaths();
16973                } catch (PackageParserException e) {
16974                    // Ignored; we tried our best
16975                }
16976            }
16977
16978            cleanUp();
16979            removeDexFiles(allCodePaths, instructionSets);
16980        }
16981
16982        boolean doPostDeleteLI(boolean delete) {
16983            // XXX err, shouldn't we respect the delete flag?
16984            cleanUpResourcesLI();
16985            return true;
16986        }
16987    }
16988
16989    private boolean isAsecExternal(String cid) {
16990        final String asecPath = PackageHelper.getSdFilesystem(cid);
16991        return !asecPath.startsWith(mAsecInternalPath);
16992    }
16993
16994    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16995            PackageManagerException {
16996        if (copyRet < 0) {
16997            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16998                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16999                throw new PackageManagerException(copyRet, message);
17000            }
17001        }
17002    }
17003
17004    /**
17005     * Extract the StorageManagerService "container ID" from the full code path of an
17006     * .apk.
17007     */
17008    static String cidFromCodePath(String fullCodePath) {
17009        int eidx = fullCodePath.lastIndexOf("/");
17010        String subStr1 = fullCodePath.substring(0, eidx);
17011        int sidx = subStr1.lastIndexOf("/");
17012        return subStr1.substring(sidx+1, eidx);
17013    }
17014
17015    /**
17016     * Logic to handle installation of ASEC applications, including copying and
17017     * renaming logic.
17018     */
17019    class AsecInstallArgs extends InstallArgs {
17020        static final String RES_FILE_NAME = "pkg.apk";
17021        static final String PUBLIC_RES_FILE_NAME = "res.zip";
17022
17023        String cid;
17024        String packagePath;
17025        String resourcePath;
17026
17027        /** New install */
17028        AsecInstallArgs(InstallParams params) {
17029            super(params.origin, params.move, params.observer, params.installFlags,
17030                    params.installerPackageName, params.volumeUuid,
17031                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17032                    params.grantedRuntimePermissions,
17033                    params.traceMethod, params.traceCookie, params.certificates,
17034                    params.installReason);
17035        }
17036
17037        /** Existing install */
17038        AsecInstallArgs(String fullCodePath, String[] instructionSets,
17039                        boolean isExternal, boolean isForwardLocked) {
17040            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
17041                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17042                    instructionSets, null, null, null, 0, null /*certificates*/,
17043                    PackageManager.INSTALL_REASON_UNKNOWN);
17044            // Hackily pretend we're still looking at a full code path
17045            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
17046                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
17047            }
17048
17049            // Extract cid from fullCodePath
17050            int eidx = fullCodePath.lastIndexOf("/");
17051            String subStr1 = fullCodePath.substring(0, eidx);
17052            int sidx = subStr1.lastIndexOf("/");
17053            cid = subStr1.substring(sidx+1, eidx);
17054            setMountPath(subStr1);
17055        }
17056
17057        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
17058            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
17059                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17060                    instructionSets, null, null, null, 0, null /*certificates*/,
17061                    PackageManager.INSTALL_REASON_UNKNOWN);
17062            this.cid = cid;
17063            setMountPath(PackageHelper.getSdDir(cid));
17064        }
17065
17066        void createCopyFile() {
17067            cid = mInstallerService.allocateExternalStageCidLegacy();
17068        }
17069
17070        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
17071            if (origin.staged && origin.cid != null) {
17072                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
17073                cid = origin.cid;
17074                setMountPath(PackageHelper.getSdDir(cid));
17075                return PackageManager.INSTALL_SUCCEEDED;
17076            }
17077
17078            if (temp) {
17079                createCopyFile();
17080            } else {
17081                /*
17082                 * Pre-emptively destroy the container since it's destroyed if
17083                 * copying fails due to it existing anyway.
17084                 */
17085                PackageHelper.destroySdDir(cid);
17086            }
17087
17088            final String newMountPath = imcs.copyPackageToContainer(
17089                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
17090                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
17091
17092            if (newMountPath != null) {
17093                setMountPath(newMountPath);
17094                return PackageManager.INSTALL_SUCCEEDED;
17095            } else {
17096                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17097            }
17098        }
17099
17100        @Override
17101        String getCodePath() {
17102            return packagePath;
17103        }
17104
17105        @Override
17106        String getResourcePath() {
17107            return resourcePath;
17108        }
17109
17110        int doPreInstall(int status) {
17111            if (status != PackageManager.INSTALL_SUCCEEDED) {
17112                // Destroy container
17113                PackageHelper.destroySdDir(cid);
17114            } else {
17115                boolean mounted = PackageHelper.isContainerMounted(cid);
17116                if (!mounted) {
17117                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17118                            Process.SYSTEM_UID);
17119                    if (newMountPath != null) {
17120                        setMountPath(newMountPath);
17121                    } else {
17122                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17123                    }
17124                }
17125            }
17126            return status;
17127        }
17128
17129        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17130            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17131            String newMountPath = null;
17132            if (PackageHelper.isContainerMounted(cid)) {
17133                // Unmount the container
17134                if (!PackageHelper.unMountSdDir(cid)) {
17135                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17136                    return false;
17137                }
17138            }
17139            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17140                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17141                        " which might be stale. Will try to clean up.");
17142                // Clean up the stale container and proceed to recreate.
17143                if (!PackageHelper.destroySdDir(newCacheId)) {
17144                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17145                    return false;
17146                }
17147                // Successfully cleaned up stale container. Try to rename again.
17148                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17149                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17150                            + " inspite of cleaning it up.");
17151                    return false;
17152                }
17153            }
17154            if (!PackageHelper.isContainerMounted(newCacheId)) {
17155                Slog.w(TAG, "Mounting container " + newCacheId);
17156                newMountPath = PackageHelper.mountSdDir(newCacheId,
17157                        getEncryptKey(), Process.SYSTEM_UID);
17158            } else {
17159                newMountPath = PackageHelper.getSdDir(newCacheId);
17160            }
17161            if (newMountPath == null) {
17162                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17163                return false;
17164            }
17165            Log.i(TAG, "Succesfully renamed " + cid +
17166                    " to " + newCacheId +
17167                    " at new path: " + newMountPath);
17168            cid = newCacheId;
17169
17170            final File beforeCodeFile = new File(packagePath);
17171            setMountPath(newMountPath);
17172            final File afterCodeFile = new File(packagePath);
17173
17174            // Reflect the rename in scanned details
17175            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17176            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17177                    afterCodeFile, pkg.baseCodePath));
17178            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17179                    afterCodeFile, pkg.splitCodePaths));
17180
17181            // Reflect the rename in app info
17182            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17183            pkg.setApplicationInfoCodePath(pkg.codePath);
17184            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17185            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17186            pkg.setApplicationInfoResourcePath(pkg.codePath);
17187            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17188            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17189
17190            return true;
17191        }
17192
17193        private void setMountPath(String mountPath) {
17194            final File mountFile = new File(mountPath);
17195
17196            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17197            if (monolithicFile.exists()) {
17198                packagePath = monolithicFile.getAbsolutePath();
17199                if (isFwdLocked()) {
17200                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17201                } else {
17202                    resourcePath = packagePath;
17203                }
17204            } else {
17205                packagePath = mountFile.getAbsolutePath();
17206                resourcePath = packagePath;
17207            }
17208        }
17209
17210        int doPostInstall(int status, int uid) {
17211            if (status != PackageManager.INSTALL_SUCCEEDED) {
17212                cleanUp();
17213            } else {
17214                final int groupOwner;
17215                final String protectedFile;
17216                if (isFwdLocked()) {
17217                    groupOwner = UserHandle.getSharedAppGid(uid);
17218                    protectedFile = RES_FILE_NAME;
17219                } else {
17220                    groupOwner = -1;
17221                    protectedFile = null;
17222                }
17223
17224                if (uid < Process.FIRST_APPLICATION_UID
17225                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17226                    Slog.e(TAG, "Failed to finalize " + cid);
17227                    PackageHelper.destroySdDir(cid);
17228                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17229                }
17230
17231                boolean mounted = PackageHelper.isContainerMounted(cid);
17232                if (!mounted) {
17233                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17234                }
17235            }
17236            return status;
17237        }
17238
17239        private void cleanUp() {
17240            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17241
17242            // Destroy secure container
17243            PackageHelper.destroySdDir(cid);
17244        }
17245
17246        private List<String> getAllCodePaths() {
17247            final File codeFile = new File(getCodePath());
17248            if (codeFile != null && codeFile.exists()) {
17249                try {
17250                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17251                    return pkg.getAllCodePaths();
17252                } catch (PackageParserException e) {
17253                    // Ignored; we tried our best
17254                }
17255            }
17256            return Collections.EMPTY_LIST;
17257        }
17258
17259        void cleanUpResourcesLI() {
17260            // Enumerate all code paths before deleting
17261            cleanUpResourcesLI(getAllCodePaths());
17262        }
17263
17264        private void cleanUpResourcesLI(List<String> allCodePaths) {
17265            cleanUp();
17266            removeDexFiles(allCodePaths, instructionSets);
17267        }
17268
17269        String getPackageName() {
17270            return getAsecPackageName(cid);
17271        }
17272
17273        boolean doPostDeleteLI(boolean delete) {
17274            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17275            final List<String> allCodePaths = getAllCodePaths();
17276            boolean mounted = PackageHelper.isContainerMounted(cid);
17277            if (mounted) {
17278                // Unmount first
17279                if (PackageHelper.unMountSdDir(cid)) {
17280                    mounted = false;
17281                }
17282            }
17283            if (!mounted && delete) {
17284                cleanUpResourcesLI(allCodePaths);
17285            }
17286            return !mounted;
17287        }
17288
17289        @Override
17290        int doPreCopy() {
17291            if (isFwdLocked()) {
17292                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17293                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17294                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17295                }
17296            }
17297
17298            return PackageManager.INSTALL_SUCCEEDED;
17299        }
17300
17301        @Override
17302        int doPostCopy(int uid) {
17303            if (isFwdLocked()) {
17304                if (uid < Process.FIRST_APPLICATION_UID
17305                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17306                                RES_FILE_NAME)) {
17307                    Slog.e(TAG, "Failed to finalize " + cid);
17308                    PackageHelper.destroySdDir(cid);
17309                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17310                }
17311            }
17312
17313            return PackageManager.INSTALL_SUCCEEDED;
17314        }
17315    }
17316
17317    /**
17318     * Logic to handle movement of existing installed applications.
17319     */
17320    class MoveInstallArgs extends InstallArgs {
17321        private File codeFile;
17322        private File resourceFile;
17323
17324        /** New install */
17325        MoveInstallArgs(InstallParams params) {
17326            super(params.origin, params.move, params.observer, params.installFlags,
17327                    params.installerPackageName, params.volumeUuid,
17328                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17329                    params.grantedRuntimePermissions,
17330                    params.traceMethod, params.traceCookie, params.certificates,
17331                    params.installReason);
17332        }
17333
17334        int copyApk(IMediaContainerService imcs, boolean temp) {
17335            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17336                    + move.fromUuid + " to " + move.toUuid);
17337            synchronized (mInstaller) {
17338                try {
17339                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17340                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17341                } catch (InstallerException e) {
17342                    Slog.w(TAG, "Failed to move app", e);
17343                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17344                }
17345            }
17346
17347            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17348            resourceFile = codeFile;
17349            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17350
17351            return PackageManager.INSTALL_SUCCEEDED;
17352        }
17353
17354        int doPreInstall(int status) {
17355            if (status != PackageManager.INSTALL_SUCCEEDED) {
17356                cleanUp(move.toUuid);
17357            }
17358            return status;
17359        }
17360
17361        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17362            if (status != PackageManager.INSTALL_SUCCEEDED) {
17363                cleanUp(move.toUuid);
17364                return false;
17365            }
17366
17367            // Reflect the move in app info
17368            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17369            pkg.setApplicationInfoCodePath(pkg.codePath);
17370            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17371            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17372            pkg.setApplicationInfoResourcePath(pkg.codePath);
17373            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17374            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17375
17376            return true;
17377        }
17378
17379        int doPostInstall(int status, int uid) {
17380            if (status == PackageManager.INSTALL_SUCCEEDED) {
17381                cleanUp(move.fromUuid);
17382            } else {
17383                cleanUp(move.toUuid);
17384            }
17385            return status;
17386        }
17387
17388        @Override
17389        String getCodePath() {
17390            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17391        }
17392
17393        @Override
17394        String getResourcePath() {
17395            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17396        }
17397
17398        private boolean cleanUp(String volumeUuid) {
17399            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17400                    move.dataAppName);
17401            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17402            final int[] userIds = sUserManager.getUserIds();
17403            synchronized (mInstallLock) {
17404                // Clean up both app data and code
17405                // All package moves are frozen until finished
17406                for (int userId : userIds) {
17407                    try {
17408                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17409                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17410                    } catch (InstallerException e) {
17411                        Slog.w(TAG, String.valueOf(e));
17412                    }
17413                }
17414                removeCodePathLI(codeFile);
17415            }
17416            return true;
17417        }
17418
17419        void cleanUpResourcesLI() {
17420            throw new UnsupportedOperationException();
17421        }
17422
17423        boolean doPostDeleteLI(boolean delete) {
17424            throw new UnsupportedOperationException();
17425        }
17426    }
17427
17428    static String getAsecPackageName(String packageCid) {
17429        int idx = packageCid.lastIndexOf("-");
17430        if (idx == -1) {
17431            return packageCid;
17432        }
17433        return packageCid.substring(0, idx);
17434    }
17435
17436    // Utility method used to create code paths based on package name and available index.
17437    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17438        String idxStr = "";
17439        int idx = 1;
17440        // Fall back to default value of idx=1 if prefix is not
17441        // part of oldCodePath
17442        if (oldCodePath != null) {
17443            String subStr = oldCodePath;
17444            // Drop the suffix right away
17445            if (suffix != null && subStr.endsWith(suffix)) {
17446                subStr = subStr.substring(0, subStr.length() - suffix.length());
17447            }
17448            // If oldCodePath already contains prefix find out the
17449            // ending index to either increment or decrement.
17450            int sidx = subStr.lastIndexOf(prefix);
17451            if (sidx != -1) {
17452                subStr = subStr.substring(sidx + prefix.length());
17453                if (subStr != null) {
17454                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17455                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17456                    }
17457                    try {
17458                        idx = Integer.parseInt(subStr);
17459                        if (idx <= 1) {
17460                            idx++;
17461                        } else {
17462                            idx--;
17463                        }
17464                    } catch(NumberFormatException e) {
17465                    }
17466                }
17467            }
17468        }
17469        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17470        return prefix + idxStr;
17471    }
17472
17473    private File getNextCodePath(File targetDir, String packageName) {
17474        File result;
17475        SecureRandom random = new SecureRandom();
17476        byte[] bytes = new byte[16];
17477        do {
17478            random.nextBytes(bytes);
17479            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17480            result = new File(targetDir, packageName + "-" + suffix);
17481        } while (result.exists());
17482        return result;
17483    }
17484
17485    // Utility method that returns the relative package path with respect
17486    // to the installation directory. Like say for /data/data/com.test-1.apk
17487    // string com.test-1 is returned.
17488    static String deriveCodePathName(String codePath) {
17489        if (codePath == null) {
17490            return null;
17491        }
17492        final File codeFile = new File(codePath);
17493        final String name = codeFile.getName();
17494        if (codeFile.isDirectory()) {
17495            return name;
17496        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17497            final int lastDot = name.lastIndexOf('.');
17498            return name.substring(0, lastDot);
17499        } else {
17500            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17501            return null;
17502        }
17503    }
17504
17505    static class PackageInstalledInfo {
17506        String name;
17507        int uid;
17508        // The set of users that originally had this package installed.
17509        int[] origUsers;
17510        // The set of users that now have this package installed.
17511        int[] newUsers;
17512        PackageParser.Package pkg;
17513        int returnCode;
17514        String returnMsg;
17515        String installerPackageName;
17516        PackageRemovedInfo removedInfo;
17517        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17518
17519        public void setError(int code, String msg) {
17520            setReturnCode(code);
17521            setReturnMessage(msg);
17522            Slog.w(TAG, msg);
17523        }
17524
17525        public void setError(String msg, PackageParserException e) {
17526            setReturnCode(e.error);
17527            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17528            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17529            for (int i = 0; i < childCount; i++) {
17530                addedChildPackages.valueAt(i).setError(msg, e);
17531            }
17532            Slog.w(TAG, msg, e);
17533        }
17534
17535        public void setError(String msg, PackageManagerException e) {
17536            returnCode = e.error;
17537            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17538            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17539            for (int i = 0; i < childCount; i++) {
17540                addedChildPackages.valueAt(i).setError(msg, e);
17541            }
17542            Slog.w(TAG, msg, e);
17543        }
17544
17545        public void setReturnCode(int returnCode) {
17546            this.returnCode = returnCode;
17547            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17548            for (int i = 0; i < childCount; i++) {
17549                addedChildPackages.valueAt(i).returnCode = returnCode;
17550            }
17551        }
17552
17553        private void setReturnMessage(String returnMsg) {
17554            this.returnMsg = returnMsg;
17555            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17556            for (int i = 0; i < childCount; i++) {
17557                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17558            }
17559        }
17560
17561        // In some error cases we want to convey more info back to the observer
17562        String origPackage;
17563        String origPermission;
17564    }
17565
17566    /*
17567     * Install a non-existing package.
17568     */
17569    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17570            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17571            PackageInstalledInfo res, int installReason) {
17572        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17573
17574        // Remember this for later, in case we need to rollback this install
17575        String pkgName = pkg.packageName;
17576
17577        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17578
17579        synchronized(mPackages) {
17580            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17581            if (renamedPackage != null) {
17582                // A package with the same name is already installed, though
17583                // it has been renamed to an older name.  The package we
17584                // are trying to install should be installed as an update to
17585                // the existing one, but that has not been requested, so bail.
17586                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17587                        + " without first uninstalling package running as "
17588                        + renamedPackage);
17589                return;
17590            }
17591            if (mPackages.containsKey(pkgName)) {
17592                // Don't allow installation over an existing package with the same name.
17593                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17594                        + " without first uninstalling.");
17595                return;
17596            }
17597        }
17598
17599        try {
17600            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17601                    System.currentTimeMillis(), user);
17602
17603            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17604
17605            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17606                prepareAppDataAfterInstallLIF(newPackage);
17607
17608            } else {
17609                // Remove package from internal structures, but keep around any
17610                // data that might have already existed
17611                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17612                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17613            }
17614        } catch (PackageManagerException e) {
17615            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17616        }
17617
17618        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17619    }
17620
17621    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17622        // Can't rotate keys during boot or if sharedUser.
17623        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17624                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17625            return false;
17626        }
17627        // app is using upgradeKeySets; make sure all are valid
17628        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17629        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17630        for (int i = 0; i < upgradeKeySets.length; i++) {
17631            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17632                Slog.wtf(TAG, "Package "
17633                         + (oldPs.name != null ? oldPs.name : "<null>")
17634                         + " contains upgrade-key-set reference to unknown key-set: "
17635                         + upgradeKeySets[i]
17636                         + " reverting to signatures check.");
17637                return false;
17638            }
17639        }
17640        return true;
17641    }
17642
17643    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17644        // Upgrade keysets are being used.  Determine if new package has a superset of the
17645        // required keys.
17646        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17647        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17648        for (int i = 0; i < upgradeKeySets.length; i++) {
17649            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17650            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17651                return true;
17652            }
17653        }
17654        return false;
17655    }
17656
17657    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17658        try (DigestInputStream digestStream =
17659                new DigestInputStream(new FileInputStream(file), digest)) {
17660            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17661        }
17662    }
17663
17664    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17665            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17666            int installReason) {
17667        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17668
17669        final PackageParser.Package oldPackage;
17670        final PackageSetting ps;
17671        final String pkgName = pkg.packageName;
17672        final int[] allUsers;
17673        final int[] installedUsers;
17674
17675        synchronized(mPackages) {
17676            oldPackage = mPackages.get(pkgName);
17677            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17678
17679            // don't allow upgrade to target a release SDK from a pre-release SDK
17680            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17681                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17682            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17683                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17684            if (oldTargetsPreRelease
17685                    && !newTargetsPreRelease
17686                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17687                Slog.w(TAG, "Can't install package targeting released sdk");
17688                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17689                return;
17690            }
17691
17692            ps = mSettings.mPackages.get(pkgName);
17693
17694            // verify signatures are valid
17695            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17696                if (!checkUpgradeKeySetLP(ps, pkg)) {
17697                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17698                            "New package not signed by keys specified by upgrade-keysets: "
17699                                    + pkgName);
17700                    return;
17701                }
17702            } else {
17703                // default to original signature matching
17704                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17705                        != PackageManager.SIGNATURE_MATCH) {
17706                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17707                            "New package has a different signature: " + pkgName);
17708                    return;
17709                }
17710            }
17711
17712            // don't allow a system upgrade unless the upgrade hash matches
17713            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17714                byte[] digestBytes = null;
17715                try {
17716                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17717                    updateDigest(digest, new File(pkg.baseCodePath));
17718                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17719                        for (String path : pkg.splitCodePaths) {
17720                            updateDigest(digest, new File(path));
17721                        }
17722                    }
17723                    digestBytes = digest.digest();
17724                } catch (NoSuchAlgorithmException | IOException e) {
17725                    res.setError(INSTALL_FAILED_INVALID_APK,
17726                            "Could not compute hash: " + pkgName);
17727                    return;
17728                }
17729                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17730                    res.setError(INSTALL_FAILED_INVALID_APK,
17731                            "New package fails restrict-update check: " + pkgName);
17732                    return;
17733                }
17734                // retain upgrade restriction
17735                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17736            }
17737
17738            // Check for shared user id changes
17739            String invalidPackageName =
17740                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17741            if (invalidPackageName != null) {
17742                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17743                        "Package " + invalidPackageName + " tried to change user "
17744                                + oldPackage.mSharedUserId);
17745                return;
17746            }
17747
17748            // check if the new package supports all of the abis which the old package supports
17749            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
17750            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
17751            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
17752                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17753                        "Update to package " + pkgName + " doesn't support multi arch");
17754                return;
17755            }
17756
17757            // In case of rollback, remember per-user/profile install state
17758            allUsers = sUserManager.getUserIds();
17759            installedUsers = ps.queryInstalledUsers(allUsers, true);
17760
17761            // don't allow an upgrade from full to ephemeral
17762            if (isInstantApp) {
17763                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17764                    for (int currentUser : allUsers) {
17765                        if (!ps.getInstantApp(currentUser)) {
17766                            // can't downgrade from full to instant
17767                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17768                                    + " for user: " + currentUser);
17769                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17770                            return;
17771                        }
17772                    }
17773                } else if (!ps.getInstantApp(user.getIdentifier())) {
17774                    // can't downgrade from full to instant
17775                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17776                            + " for user: " + user.getIdentifier());
17777                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17778                    return;
17779                }
17780            }
17781        }
17782
17783        // Update what is removed
17784        res.removedInfo = new PackageRemovedInfo(this);
17785        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17786        res.removedInfo.removedPackage = oldPackage.packageName;
17787        res.removedInfo.installerPackageName = ps.installerPackageName;
17788        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17789        res.removedInfo.isUpdate = true;
17790        res.removedInfo.origUsers = installedUsers;
17791        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17792        for (int i = 0; i < installedUsers.length; i++) {
17793            final int userId = installedUsers[i];
17794            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17795        }
17796
17797        final int childCount = (oldPackage.childPackages != null)
17798                ? oldPackage.childPackages.size() : 0;
17799        for (int i = 0; i < childCount; i++) {
17800            boolean childPackageUpdated = false;
17801            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17802            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17803            if (res.addedChildPackages != null) {
17804                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17805                if (childRes != null) {
17806                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17807                    childRes.removedInfo.removedPackage = childPkg.packageName;
17808                    if (childPs != null) {
17809                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17810                    }
17811                    childRes.removedInfo.isUpdate = true;
17812                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17813                    childPackageUpdated = true;
17814                }
17815            }
17816            if (!childPackageUpdated) {
17817                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17818                childRemovedRes.removedPackage = childPkg.packageName;
17819                if (childPs != null) {
17820                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17821                }
17822                childRemovedRes.isUpdate = false;
17823                childRemovedRes.dataRemoved = true;
17824                synchronized (mPackages) {
17825                    if (childPs != null) {
17826                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17827                    }
17828                }
17829                if (res.removedInfo.removedChildPackages == null) {
17830                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17831                }
17832                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17833            }
17834        }
17835
17836        boolean sysPkg = (isSystemApp(oldPackage));
17837        if (sysPkg) {
17838            // Set the system/privileged flags as needed
17839            final boolean privileged =
17840                    (oldPackage.applicationInfo.privateFlags
17841                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17842            final int systemPolicyFlags = policyFlags
17843                    | PackageParser.PARSE_IS_SYSTEM
17844                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17845
17846            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17847                    user, allUsers, installerPackageName, res, installReason);
17848        } else {
17849            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17850                    user, allUsers, installerPackageName, res, installReason);
17851        }
17852    }
17853
17854    @Override
17855    public List<String> getPreviousCodePaths(String packageName) {
17856        final int callingUid = Binder.getCallingUid();
17857        final List<String> result = new ArrayList<>();
17858        if (getInstantAppPackageName(callingUid) != null) {
17859            return result;
17860        }
17861        final PackageSetting ps = mSettings.mPackages.get(packageName);
17862        if (ps != null
17863                && ps.oldCodePaths != null
17864                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17865            result.addAll(ps.oldCodePaths);
17866        }
17867        return result;
17868    }
17869
17870    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17871            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17872            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17873            int installReason) {
17874        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17875                + deletedPackage);
17876
17877        String pkgName = deletedPackage.packageName;
17878        boolean deletedPkg = true;
17879        boolean addedPkg = false;
17880        boolean updatedSettings = false;
17881        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17882        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17883                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17884
17885        final long origUpdateTime = (pkg.mExtras != null)
17886                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17887
17888        // First delete the existing package while retaining the data directory
17889        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17890                res.removedInfo, true, pkg)) {
17891            // If the existing package wasn't successfully deleted
17892            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17893            deletedPkg = false;
17894        } else {
17895            // Successfully deleted the old package; proceed with replace.
17896
17897            // If deleted package lived in a container, give users a chance to
17898            // relinquish resources before killing.
17899            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17900                if (DEBUG_INSTALL) {
17901                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17902                }
17903                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17904                final ArrayList<String> pkgList = new ArrayList<String>(1);
17905                pkgList.add(deletedPackage.applicationInfo.packageName);
17906                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17907            }
17908
17909            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17910                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17911            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17912
17913            try {
17914                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17915                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17916                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17917                        installReason);
17918
17919                // Update the in-memory copy of the previous code paths.
17920                PackageSetting ps = mSettings.mPackages.get(pkgName);
17921                if (!killApp) {
17922                    if (ps.oldCodePaths == null) {
17923                        ps.oldCodePaths = new ArraySet<>();
17924                    }
17925                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17926                    if (deletedPackage.splitCodePaths != null) {
17927                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17928                    }
17929                } else {
17930                    ps.oldCodePaths = null;
17931                }
17932                if (ps.childPackageNames != null) {
17933                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17934                        final String childPkgName = ps.childPackageNames.get(i);
17935                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17936                        childPs.oldCodePaths = ps.oldCodePaths;
17937                    }
17938                }
17939                // set instant app status, but, only if it's explicitly specified
17940                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17941                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17942                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17943                prepareAppDataAfterInstallLIF(newPackage);
17944                addedPkg = true;
17945                mDexManager.notifyPackageUpdated(newPackage.packageName,
17946                        newPackage.baseCodePath, newPackage.splitCodePaths);
17947            } catch (PackageManagerException e) {
17948                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17949            }
17950        }
17951
17952        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17953            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17954
17955            // Revert all internal state mutations and added folders for the failed install
17956            if (addedPkg) {
17957                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17958                        res.removedInfo, true, null);
17959            }
17960
17961            // Restore the old package
17962            if (deletedPkg) {
17963                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17964                File restoreFile = new File(deletedPackage.codePath);
17965                // Parse old package
17966                boolean oldExternal = isExternal(deletedPackage);
17967                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17968                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17969                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17970                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17971                try {
17972                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17973                            null);
17974                } catch (PackageManagerException e) {
17975                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17976                            + e.getMessage());
17977                    return;
17978                }
17979
17980                synchronized (mPackages) {
17981                    // Ensure the installer package name up to date
17982                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17983
17984                    // Update permissions for restored package
17985                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17986
17987                    mSettings.writeLPr();
17988                }
17989
17990                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17991            }
17992        } else {
17993            synchronized (mPackages) {
17994                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17995                if (ps != null) {
17996                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17997                    if (res.removedInfo.removedChildPackages != null) {
17998                        final int childCount = res.removedInfo.removedChildPackages.size();
17999                        // Iterate in reverse as we may modify the collection
18000                        for (int i = childCount - 1; i >= 0; i--) {
18001                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
18002                            if (res.addedChildPackages.containsKey(childPackageName)) {
18003                                res.removedInfo.removedChildPackages.removeAt(i);
18004                            } else {
18005                                PackageRemovedInfo childInfo = res.removedInfo
18006                                        .removedChildPackages.valueAt(i);
18007                                childInfo.removedForAllUsers = mPackages.get(
18008                                        childInfo.removedPackage) == null;
18009                            }
18010                        }
18011                    }
18012                }
18013            }
18014        }
18015    }
18016
18017    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
18018            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
18019            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
18020            int installReason) {
18021        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
18022                + ", old=" + deletedPackage);
18023
18024        final boolean disabledSystem;
18025
18026        // Remove existing system package
18027        removePackageLI(deletedPackage, true);
18028
18029        synchronized (mPackages) {
18030            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
18031        }
18032        if (!disabledSystem) {
18033            // We didn't need to disable the .apk as a current system package,
18034            // which means we are replacing another update that is already
18035            // installed.  We need to make sure to delete the older one's .apk.
18036            res.removedInfo.args = createInstallArgsForExisting(0,
18037                    deletedPackage.applicationInfo.getCodePath(),
18038                    deletedPackage.applicationInfo.getResourcePath(),
18039                    getAppDexInstructionSets(deletedPackage.applicationInfo));
18040        } else {
18041            res.removedInfo.args = null;
18042        }
18043
18044        // Successfully disabled the old package. Now proceed with re-installation
18045        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
18046                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18047        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
18048
18049        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18050        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
18051                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
18052
18053        PackageParser.Package newPackage = null;
18054        try {
18055            // Add the package to the internal data structures
18056            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
18057
18058            // Set the update and install times
18059            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
18060            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
18061                    System.currentTimeMillis());
18062
18063            // Update the package dynamic state if succeeded
18064            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18065                // Now that the install succeeded make sure we remove data
18066                // directories for any child package the update removed.
18067                final int deletedChildCount = (deletedPackage.childPackages != null)
18068                        ? deletedPackage.childPackages.size() : 0;
18069                final int newChildCount = (newPackage.childPackages != null)
18070                        ? newPackage.childPackages.size() : 0;
18071                for (int i = 0; i < deletedChildCount; i++) {
18072                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
18073                    boolean childPackageDeleted = true;
18074                    for (int j = 0; j < newChildCount; j++) {
18075                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
18076                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
18077                            childPackageDeleted = false;
18078                            break;
18079                        }
18080                    }
18081                    if (childPackageDeleted) {
18082                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
18083                                deletedChildPkg.packageName);
18084                        if (ps != null && res.removedInfo.removedChildPackages != null) {
18085                            PackageRemovedInfo removedChildRes = res.removedInfo
18086                                    .removedChildPackages.get(deletedChildPkg.packageName);
18087                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
18088                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
18089                        }
18090                    }
18091                }
18092
18093                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
18094                        installReason);
18095                prepareAppDataAfterInstallLIF(newPackage);
18096
18097                mDexManager.notifyPackageUpdated(newPackage.packageName,
18098                            newPackage.baseCodePath, newPackage.splitCodePaths);
18099            }
18100        } catch (PackageManagerException e) {
18101            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
18102            res.setError("Package couldn't be installed in " + pkg.codePath, e);
18103        }
18104
18105        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
18106            // Re installation failed. Restore old information
18107            // Remove new pkg information
18108            if (newPackage != null) {
18109                removeInstalledPackageLI(newPackage, true);
18110            }
18111            // Add back the old system package
18112            try {
18113                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
18114            } catch (PackageManagerException e) {
18115                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
18116            }
18117
18118            synchronized (mPackages) {
18119                if (disabledSystem) {
18120                    enableSystemPackageLPw(deletedPackage);
18121                }
18122
18123                // Ensure the installer package name up to date
18124                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18125
18126                // Update permissions for restored package
18127                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18128
18129                mSettings.writeLPr();
18130            }
18131
18132            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18133                    + " after failed upgrade");
18134        }
18135    }
18136
18137    /**
18138     * Checks whether the parent or any of the child packages have a change shared
18139     * user. For a package to be a valid update the shred users of the parent and
18140     * the children should match. We may later support changing child shared users.
18141     * @param oldPkg The updated package.
18142     * @param newPkg The update package.
18143     * @return The shared user that change between the versions.
18144     */
18145    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18146            PackageParser.Package newPkg) {
18147        // Check parent shared user
18148        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18149            return newPkg.packageName;
18150        }
18151        // Check child shared users
18152        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18153        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18154        for (int i = 0; i < newChildCount; i++) {
18155            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18156            // If this child was present, did it have the same shared user?
18157            for (int j = 0; j < oldChildCount; j++) {
18158                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18159                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18160                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18161                    return newChildPkg.packageName;
18162                }
18163            }
18164        }
18165        return null;
18166    }
18167
18168    private void removeNativeBinariesLI(PackageSetting ps) {
18169        // Remove the lib path for the parent package
18170        if (ps != null) {
18171            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18172            // Remove the lib path for the child packages
18173            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18174            for (int i = 0; i < childCount; i++) {
18175                PackageSetting childPs = null;
18176                synchronized (mPackages) {
18177                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18178                }
18179                if (childPs != null) {
18180                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18181                            .legacyNativeLibraryPathString);
18182                }
18183            }
18184        }
18185    }
18186
18187    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18188        // Enable the parent package
18189        mSettings.enableSystemPackageLPw(pkg.packageName);
18190        // Enable the child packages
18191        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18192        for (int i = 0; i < childCount; i++) {
18193            PackageParser.Package childPkg = pkg.childPackages.get(i);
18194            mSettings.enableSystemPackageLPw(childPkg.packageName);
18195        }
18196    }
18197
18198    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18199            PackageParser.Package newPkg) {
18200        // Disable the parent package (parent always replaced)
18201        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18202        // Disable the child packages
18203        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18204        for (int i = 0; i < childCount; i++) {
18205            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18206            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18207            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18208        }
18209        return disabled;
18210    }
18211
18212    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18213            String installerPackageName) {
18214        // Enable the parent package
18215        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18216        // Enable the child packages
18217        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18218        for (int i = 0; i < childCount; i++) {
18219            PackageParser.Package childPkg = pkg.childPackages.get(i);
18220            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18221        }
18222    }
18223
18224    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18225        // Collect all used permissions in the UID
18226        ArraySet<String> usedPermissions = new ArraySet<>();
18227        final int packageCount = su.packages.size();
18228        for (int i = 0; i < packageCount; i++) {
18229            PackageSetting ps = su.packages.valueAt(i);
18230            if (ps.pkg == null) {
18231                continue;
18232            }
18233            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18234            for (int j = 0; j < requestedPermCount; j++) {
18235                String permission = ps.pkg.requestedPermissions.get(j);
18236                BasePermission bp = mSettings.mPermissions.get(permission);
18237                if (bp != null) {
18238                    usedPermissions.add(permission);
18239                }
18240            }
18241        }
18242
18243        PermissionsState permissionsState = su.getPermissionsState();
18244        // Prune install permissions
18245        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18246        final int installPermCount = installPermStates.size();
18247        for (int i = installPermCount - 1; i >= 0;  i--) {
18248            PermissionState permissionState = installPermStates.get(i);
18249            if (!usedPermissions.contains(permissionState.getName())) {
18250                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18251                if (bp != null) {
18252                    permissionsState.revokeInstallPermission(bp);
18253                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18254                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18255                }
18256            }
18257        }
18258
18259        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18260
18261        // Prune runtime permissions
18262        for (int userId : allUserIds) {
18263            List<PermissionState> runtimePermStates = permissionsState
18264                    .getRuntimePermissionStates(userId);
18265            final int runtimePermCount = runtimePermStates.size();
18266            for (int i = runtimePermCount - 1; i >= 0; i--) {
18267                PermissionState permissionState = runtimePermStates.get(i);
18268                if (!usedPermissions.contains(permissionState.getName())) {
18269                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18270                    if (bp != null) {
18271                        permissionsState.revokeRuntimePermission(bp, userId);
18272                        permissionsState.updatePermissionFlags(bp, userId,
18273                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18274                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18275                                runtimePermissionChangedUserIds, userId);
18276                    }
18277                }
18278            }
18279        }
18280
18281        return runtimePermissionChangedUserIds;
18282    }
18283
18284    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18285            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18286        // Update the parent package setting
18287        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18288                res, user, installReason);
18289        // Update the child packages setting
18290        final int childCount = (newPackage.childPackages != null)
18291                ? newPackage.childPackages.size() : 0;
18292        for (int i = 0; i < childCount; i++) {
18293            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18294            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18295            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18296                    childRes.origUsers, childRes, user, installReason);
18297        }
18298    }
18299
18300    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18301            String installerPackageName, int[] allUsers, int[] installedForUsers,
18302            PackageInstalledInfo res, UserHandle user, int installReason) {
18303        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18304
18305        String pkgName = newPackage.packageName;
18306        synchronized (mPackages) {
18307            //write settings. the installStatus will be incomplete at this stage.
18308            //note that the new package setting would have already been
18309            //added to mPackages. It hasn't been persisted yet.
18310            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18311            // TODO: Remove this write? It's also written at the end of this method
18312            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18313            mSettings.writeLPr();
18314            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18315        }
18316
18317        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18318        synchronized (mPackages) {
18319            updatePermissionsLPw(newPackage.packageName, newPackage,
18320                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18321                            ? UPDATE_PERMISSIONS_ALL : 0));
18322            // For system-bundled packages, we assume that installing an upgraded version
18323            // of the package implies that the user actually wants to run that new code,
18324            // so we enable the package.
18325            PackageSetting ps = mSettings.mPackages.get(pkgName);
18326            final int userId = user.getIdentifier();
18327            if (ps != null) {
18328                if (isSystemApp(newPackage)) {
18329                    if (DEBUG_INSTALL) {
18330                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18331                    }
18332                    // Enable system package for requested users
18333                    if (res.origUsers != null) {
18334                        for (int origUserId : res.origUsers) {
18335                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18336                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18337                                        origUserId, installerPackageName);
18338                            }
18339                        }
18340                    }
18341                    // Also convey the prior install/uninstall state
18342                    if (allUsers != null && installedForUsers != null) {
18343                        for (int currentUserId : allUsers) {
18344                            final boolean installed = ArrayUtils.contains(
18345                                    installedForUsers, currentUserId);
18346                            if (DEBUG_INSTALL) {
18347                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18348                            }
18349                            ps.setInstalled(installed, currentUserId);
18350                        }
18351                        // these install state changes will be persisted in the
18352                        // upcoming call to mSettings.writeLPr().
18353                    }
18354                }
18355                // It's implied that when a user requests installation, they want the app to be
18356                // installed and enabled.
18357                if (userId != UserHandle.USER_ALL) {
18358                    ps.setInstalled(true, userId);
18359                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18360                }
18361
18362                // When replacing an existing package, preserve the original install reason for all
18363                // users that had the package installed before.
18364                final Set<Integer> previousUserIds = new ArraySet<>();
18365                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18366                    final int installReasonCount = res.removedInfo.installReasons.size();
18367                    for (int i = 0; i < installReasonCount; i++) {
18368                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18369                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18370                        ps.setInstallReason(previousInstallReason, previousUserId);
18371                        previousUserIds.add(previousUserId);
18372                    }
18373                }
18374
18375                // Set install reason for users that are having the package newly installed.
18376                if (userId == UserHandle.USER_ALL) {
18377                    for (int currentUserId : sUserManager.getUserIds()) {
18378                        if (!previousUserIds.contains(currentUserId)) {
18379                            ps.setInstallReason(installReason, currentUserId);
18380                        }
18381                    }
18382                } else if (!previousUserIds.contains(userId)) {
18383                    ps.setInstallReason(installReason, userId);
18384                }
18385                mSettings.writeKernelMappingLPr(ps);
18386            }
18387            res.name = pkgName;
18388            res.uid = newPackage.applicationInfo.uid;
18389            res.pkg = newPackage;
18390            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18391            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18392            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18393            //to update install status
18394            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18395            mSettings.writeLPr();
18396            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18397        }
18398
18399        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18400    }
18401
18402    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18403        try {
18404            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18405            installPackageLI(args, res);
18406        } finally {
18407            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18408        }
18409    }
18410
18411    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18412        final int installFlags = args.installFlags;
18413        final String installerPackageName = args.installerPackageName;
18414        final String volumeUuid = args.volumeUuid;
18415        final File tmpPackageFile = new File(args.getCodePath());
18416        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18417        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18418                || (args.volumeUuid != null));
18419        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18420        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18421        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18422        final boolean virtualPreload =
18423                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18424        boolean replace = false;
18425        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18426        if (args.move != null) {
18427            // moving a complete application; perform an initial scan on the new install location
18428            scanFlags |= SCAN_INITIAL;
18429        }
18430        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18431            scanFlags |= SCAN_DONT_KILL_APP;
18432        }
18433        if (instantApp) {
18434            scanFlags |= SCAN_AS_INSTANT_APP;
18435        }
18436        if (fullApp) {
18437            scanFlags |= SCAN_AS_FULL_APP;
18438        }
18439        if (virtualPreload) {
18440            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18441        }
18442
18443        // Result object to be returned
18444        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18445        res.installerPackageName = installerPackageName;
18446
18447        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18448
18449        // Sanity check
18450        if (instantApp && (forwardLocked || onExternal)) {
18451            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18452                    + " external=" + onExternal);
18453            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18454            return;
18455        }
18456
18457        // Retrieve PackageSettings and parse package
18458        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18459                | PackageParser.PARSE_ENFORCE_CODE
18460                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18461                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18462                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18463                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18464        PackageParser pp = new PackageParser();
18465        pp.setSeparateProcesses(mSeparateProcesses);
18466        pp.setDisplayMetrics(mMetrics);
18467        pp.setCallback(mPackageParserCallback);
18468
18469        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18470        final PackageParser.Package pkg;
18471        try {
18472            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18473            DexMetadataHelper.validatePackageDexMetadata(pkg);
18474        } catch (PackageParserException e) {
18475            res.setError("Failed parse during installPackageLI", e);
18476            return;
18477        } finally {
18478            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18479        }
18480
18481        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18482        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18483            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18484            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18485                    "Instant app package must target O");
18486            return;
18487        }
18488        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18489            Slog.w(TAG, "Instant app package " + pkg.packageName
18490                    + " does not target targetSandboxVersion 2");
18491            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18492                    "Instant app package must use targetSanboxVersion 2");
18493            return;
18494        }
18495
18496        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18497            // Static shared libraries have synthetic package names
18498            renameStaticSharedLibraryPackage(pkg);
18499
18500            // No static shared libs on external storage
18501            if (onExternal) {
18502                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18503                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18504                        "Packages declaring static-shared libs cannot be updated");
18505                return;
18506            }
18507        }
18508
18509        // If we are installing a clustered package add results for the children
18510        if (pkg.childPackages != null) {
18511            synchronized (mPackages) {
18512                final int childCount = pkg.childPackages.size();
18513                for (int i = 0; i < childCount; i++) {
18514                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18515                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18516                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18517                    childRes.pkg = childPkg;
18518                    childRes.name = childPkg.packageName;
18519                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18520                    if (childPs != null) {
18521                        childRes.origUsers = childPs.queryInstalledUsers(
18522                                sUserManager.getUserIds(), true);
18523                    }
18524                    if ((mPackages.containsKey(childPkg.packageName))) {
18525                        childRes.removedInfo = new PackageRemovedInfo(this);
18526                        childRes.removedInfo.removedPackage = childPkg.packageName;
18527                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18528                    }
18529                    if (res.addedChildPackages == null) {
18530                        res.addedChildPackages = new ArrayMap<>();
18531                    }
18532                    res.addedChildPackages.put(childPkg.packageName, childRes);
18533                }
18534            }
18535        }
18536
18537        // If package doesn't declare API override, mark that we have an install
18538        // time CPU ABI override.
18539        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18540            pkg.cpuAbiOverride = args.abiOverride;
18541        }
18542
18543        String pkgName = res.name = pkg.packageName;
18544        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18545            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18546                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18547                return;
18548            }
18549        }
18550
18551        try {
18552            // either use what we've been given or parse directly from the APK
18553            if (args.certificates != null) {
18554                try {
18555                    PackageParser.populateCertificates(pkg, args.certificates);
18556                } catch (PackageParserException e) {
18557                    // there was something wrong with the certificates we were given;
18558                    // try to pull them from the APK
18559                    PackageParser.collectCertificates(pkg, parseFlags);
18560                }
18561            } else {
18562                PackageParser.collectCertificates(pkg, parseFlags);
18563            }
18564        } catch (PackageParserException e) {
18565            res.setError("Failed collect during installPackageLI", e);
18566            return;
18567        }
18568
18569        // Get rid of all references to package scan path via parser.
18570        pp = null;
18571        String oldCodePath = null;
18572        boolean systemApp = false;
18573        synchronized (mPackages) {
18574            // Check if installing already existing package
18575            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18576                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18577                if (pkg.mOriginalPackages != null
18578                        && pkg.mOriginalPackages.contains(oldName)
18579                        && mPackages.containsKey(oldName)) {
18580                    // This package is derived from an original package,
18581                    // and this device has been updating from that original
18582                    // name.  We must continue using the original name, so
18583                    // rename the new package here.
18584                    pkg.setPackageName(oldName);
18585                    pkgName = pkg.packageName;
18586                    replace = true;
18587                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18588                            + oldName + " pkgName=" + pkgName);
18589                } else if (mPackages.containsKey(pkgName)) {
18590                    // This package, under its official name, already exists
18591                    // on the device; we should replace it.
18592                    replace = true;
18593                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18594                }
18595
18596                // Child packages are installed through the parent package
18597                if (pkg.parentPackage != null) {
18598                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18599                            "Package " + pkg.packageName + " is child of package "
18600                                    + pkg.parentPackage.parentPackage + ". Child packages "
18601                                    + "can be updated only through the parent package.");
18602                    return;
18603                }
18604
18605                if (replace) {
18606                    // Prevent apps opting out from runtime permissions
18607                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18608                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18609                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18610                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18611                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18612                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18613                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18614                                        + " doesn't support runtime permissions but the old"
18615                                        + " target SDK " + oldTargetSdk + " does.");
18616                        return;
18617                    }
18618                    // Prevent persistent apps from being updated
18619                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
18620                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
18621                                "Package " + oldPackage.packageName + " is a persistent app. "
18622                                        + "Persistent apps are not updateable.");
18623                        return;
18624                    }
18625                    // Prevent apps from downgrading their targetSandbox.
18626                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18627                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18628                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18629                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18630                                "Package " + pkg.packageName + " new target sandbox "
18631                                + newTargetSandbox + " is incompatible with the previous value of"
18632                                + oldTargetSandbox + ".");
18633                        return;
18634                    }
18635
18636                    // Prevent installing of child packages
18637                    if (oldPackage.parentPackage != null) {
18638                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18639                                "Package " + pkg.packageName + " is child of package "
18640                                        + oldPackage.parentPackage + ". Child packages "
18641                                        + "can be updated only through the parent package.");
18642                        return;
18643                    }
18644                }
18645            }
18646
18647            PackageSetting ps = mSettings.mPackages.get(pkgName);
18648            if (ps != null) {
18649                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18650
18651                // Static shared libs have same package with different versions where
18652                // we internally use a synthetic package name to allow multiple versions
18653                // of the same package, therefore we need to compare signatures against
18654                // the package setting for the latest library version.
18655                PackageSetting signatureCheckPs = ps;
18656                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18657                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18658                    if (libraryEntry != null) {
18659                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18660                    }
18661                }
18662
18663                // Quick sanity check that we're signed correctly if updating;
18664                // we'll check this again later when scanning, but we want to
18665                // bail early here before tripping over redefined permissions.
18666                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18667                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18668                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18669                                + pkg.packageName + " upgrade keys do not match the "
18670                                + "previously installed version");
18671                        return;
18672                    }
18673                } else {
18674                    try {
18675                        verifySignaturesLP(signatureCheckPs, pkg);
18676                    } catch (PackageManagerException e) {
18677                        res.setError(e.error, e.getMessage());
18678                        return;
18679                    }
18680                }
18681
18682                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18683                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18684                    systemApp = (ps.pkg.applicationInfo.flags &
18685                            ApplicationInfo.FLAG_SYSTEM) != 0;
18686                }
18687                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18688            }
18689
18690            int N = pkg.permissions.size();
18691            for (int i = N-1; i >= 0; i--) {
18692                PackageParser.Permission perm = pkg.permissions.get(i);
18693                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18694
18695                // Don't allow anyone but the system to define ephemeral permissions.
18696                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18697                        && !systemApp) {
18698                    Slog.w(TAG, "Non-System package " + pkg.packageName
18699                            + " attempting to delcare ephemeral permission "
18700                            + perm.info.name + "; Removing ephemeral.");
18701                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18702                }
18703                // Check whether the newly-scanned package wants to define an already-defined perm
18704                if (bp != null) {
18705                    // If the defining package is signed with our cert, it's okay.  This
18706                    // also includes the "updating the same package" case, of course.
18707                    // "updating same package" could also involve key-rotation.
18708                    final boolean sigsOk;
18709                    if (bp.sourcePackage.equals(pkg.packageName)
18710                            && (bp.packageSetting instanceof PackageSetting)
18711                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18712                                    scanFlags))) {
18713                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18714                    } else {
18715                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18716                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18717                    }
18718                    if (!sigsOk) {
18719                        // If the owning package is the system itself, we log but allow
18720                        // install to proceed; we fail the install on all other permission
18721                        // redefinitions.
18722                        if (!bp.sourcePackage.equals("android")) {
18723                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18724                                    + pkg.packageName + " attempting to redeclare permission "
18725                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18726                            res.origPermission = perm.info.name;
18727                            res.origPackage = bp.sourcePackage;
18728                            return;
18729                        } else {
18730                            Slog.w(TAG, "Package " + pkg.packageName
18731                                    + " attempting to redeclare system permission "
18732                                    + perm.info.name + "; ignoring new declaration");
18733                            pkg.permissions.remove(i);
18734                        }
18735                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18736                        // Prevent apps to change protection level to dangerous from any other
18737                        // type as this would allow a privilege escalation where an app adds a
18738                        // normal/signature permission in other app's group and later redefines
18739                        // it as dangerous leading to the group auto-grant.
18740                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18741                                == PermissionInfo.PROTECTION_DANGEROUS) {
18742                            if (bp != null && !bp.isRuntime()) {
18743                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18744                                        + "non-runtime permission " + perm.info.name
18745                                        + " to runtime; keeping old protection level");
18746                                perm.info.protectionLevel = bp.protectionLevel;
18747                            }
18748                        }
18749                    }
18750                }
18751            }
18752        }
18753
18754        if (systemApp) {
18755            if (onExternal) {
18756                // Abort update; system app can't be replaced with app on sdcard
18757                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18758                        "Cannot install updates to system apps on sdcard");
18759                return;
18760            } else if (instantApp) {
18761                // Abort update; system app can't be replaced with an instant app
18762                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18763                        "Cannot update a system app with an instant app");
18764                return;
18765            }
18766        }
18767
18768        if (args.move != null) {
18769            // We did an in-place move, so dex is ready to roll
18770            scanFlags |= SCAN_NO_DEX;
18771            scanFlags |= SCAN_MOVE;
18772
18773            synchronized (mPackages) {
18774                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18775                if (ps == null) {
18776                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18777                            "Missing settings for moved package " + pkgName);
18778                }
18779
18780                // We moved the entire application as-is, so bring over the
18781                // previously derived ABI information.
18782                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18783                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18784            }
18785
18786        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18787            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18788            scanFlags |= SCAN_NO_DEX;
18789
18790            try {
18791                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18792                    args.abiOverride : pkg.cpuAbiOverride);
18793                final boolean extractNativeLibs = !pkg.isLibrary();
18794                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18795                        extractNativeLibs, mAppLib32InstallDir);
18796            } catch (PackageManagerException pme) {
18797                Slog.e(TAG, "Error deriving application ABI", pme);
18798                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18799                return;
18800            }
18801
18802            // Shared libraries for the package need to be updated.
18803            synchronized (mPackages) {
18804                try {
18805                    updateSharedLibrariesLPr(pkg, null);
18806                } catch (PackageManagerException e) {
18807                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18808                }
18809            }
18810        }
18811
18812        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18813            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18814            return;
18815        }
18816
18817        if (!instantApp) {
18818            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18819        } else {
18820            if (DEBUG_DOMAIN_VERIFICATION) {
18821                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
18822            }
18823        }
18824
18825        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18826                "installPackageLI")) {
18827            if (replace) {
18828                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18829                    // Static libs have a synthetic package name containing the version
18830                    // and cannot be updated as an update would get a new package name,
18831                    // unless this is the exact same version code which is useful for
18832                    // development.
18833                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18834                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18835                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18836                                + "static-shared libs cannot be updated");
18837                        return;
18838                    }
18839                }
18840                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18841                        installerPackageName, res, args.installReason);
18842            } else {
18843                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18844                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18845            }
18846        }
18847
18848        // Check whether we need to dexopt the app.
18849        //
18850        // NOTE: it is IMPORTANT to call dexopt:
18851        //   - after doRename which will sync the package data from PackageParser.Package and its
18852        //     corresponding ApplicationInfo.
18853        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
18854        //     uid of the application (pkg.applicationInfo.uid).
18855        //     This update happens in place!
18856        //
18857        // We only need to dexopt if the package meets ALL of the following conditions:
18858        //   1) it is not forward locked.
18859        //   2) it is not on on an external ASEC container.
18860        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18861        //
18862        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18863        // complete, so we skip this step during installation. Instead, we'll take extra time
18864        // the first time the instant app starts. It's preferred to do it this way to provide
18865        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18866        // middle of running an instant app. The default behaviour can be overridden
18867        // via gservices.
18868        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
18869                && !forwardLocked
18870                && !pkg.applicationInfo.isExternalAsec()
18871                && (!instantApp || Global.getInt(mContext.getContentResolver(),
18872                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18873
18874        if (performDexopt) {
18875            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18876            // Do not run PackageDexOptimizer through the local performDexOpt
18877            // method because `pkg` may not be in `mPackages` yet.
18878            //
18879            // Also, don't fail application installs if the dexopt step fails.
18880            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18881                    REASON_INSTALL,
18882                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
18883            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18884                    null /* instructionSets */,
18885                    getOrCreateCompilerPackageStats(pkg),
18886                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18887                    dexoptOptions);
18888            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18889        }
18890
18891        // Notify BackgroundDexOptService that the package has been changed.
18892        // If this is an update of a package which used to fail to compile,
18893        // BackgroundDexOptService will remove it from its blacklist.
18894        // TODO: Layering violation
18895        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18896
18897        synchronized (mPackages) {
18898            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18899            if (ps != null) {
18900                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18901                ps.setUpdateAvailable(false /*updateAvailable*/);
18902            }
18903
18904            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18905            for (int i = 0; i < childCount; i++) {
18906                PackageParser.Package childPkg = pkg.childPackages.get(i);
18907                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18908                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18909                if (childPs != null) {
18910                    childRes.newUsers = childPs.queryInstalledUsers(
18911                            sUserManager.getUserIds(), true);
18912                }
18913            }
18914
18915            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18916                updateSequenceNumberLP(ps, res.newUsers);
18917                updateInstantAppInstallerLocked(pkgName);
18918            }
18919        }
18920    }
18921
18922    private void startIntentFilterVerifications(int userId, boolean replacing,
18923            PackageParser.Package pkg) {
18924        if (mIntentFilterVerifierComponent == null) {
18925            Slog.w(TAG, "No IntentFilter verification will not be done as "
18926                    + "there is no IntentFilterVerifier available!");
18927            return;
18928        }
18929
18930        final int verifierUid = getPackageUid(
18931                mIntentFilterVerifierComponent.getPackageName(),
18932                MATCH_DEBUG_TRIAGED_MISSING,
18933                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18934
18935        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18936        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18937        mHandler.sendMessage(msg);
18938
18939        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18940        for (int i = 0; i < childCount; i++) {
18941            PackageParser.Package childPkg = pkg.childPackages.get(i);
18942            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18943            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18944            mHandler.sendMessage(msg);
18945        }
18946    }
18947
18948    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18949            PackageParser.Package pkg) {
18950        int size = pkg.activities.size();
18951        if (size == 0) {
18952            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18953                    "No activity, so no need to verify any IntentFilter!");
18954            return;
18955        }
18956
18957        final boolean hasDomainURLs = hasDomainURLs(pkg);
18958        if (!hasDomainURLs) {
18959            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18960                    "No domain URLs, so no need to verify any IntentFilter!");
18961            return;
18962        }
18963
18964        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18965                + " if any IntentFilter from the " + size
18966                + " Activities needs verification ...");
18967
18968        int count = 0;
18969        final String packageName = pkg.packageName;
18970
18971        synchronized (mPackages) {
18972            // If this is a new install and we see that we've already run verification for this
18973            // package, we have nothing to do: it means the state was restored from backup.
18974            if (!replacing) {
18975                IntentFilterVerificationInfo ivi =
18976                        mSettings.getIntentFilterVerificationLPr(packageName);
18977                if (ivi != null) {
18978                    if (DEBUG_DOMAIN_VERIFICATION) {
18979                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18980                                + ivi.getStatusString());
18981                    }
18982                    return;
18983                }
18984            }
18985
18986            // If any filters need to be verified, then all need to be.
18987            boolean needToVerify = false;
18988            for (PackageParser.Activity a : pkg.activities) {
18989                for (ActivityIntentInfo filter : a.intents) {
18990                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18991                        if (DEBUG_DOMAIN_VERIFICATION) {
18992                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18993                        }
18994                        needToVerify = true;
18995                        break;
18996                    }
18997                }
18998            }
18999
19000            if (needToVerify) {
19001                final int verificationId = mIntentFilterVerificationToken++;
19002                for (PackageParser.Activity a : pkg.activities) {
19003                    for (ActivityIntentInfo filter : a.intents) {
19004                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
19005                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
19006                                    "Verification needed for IntentFilter:" + filter.toString());
19007                            mIntentFilterVerifier.addOneIntentFilterVerification(
19008                                    verifierUid, userId, verificationId, filter, packageName);
19009                            count++;
19010                        }
19011                    }
19012                }
19013            }
19014        }
19015
19016        if (count > 0) {
19017            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
19018                    + " IntentFilter verification" + (count > 1 ? "s" : "")
19019                    +  " for userId:" + userId);
19020            mIntentFilterVerifier.startVerifications(userId);
19021        } else {
19022            if (DEBUG_DOMAIN_VERIFICATION) {
19023                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
19024            }
19025        }
19026    }
19027
19028    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
19029        final ComponentName cn  = filter.activity.getComponentName();
19030        final String packageName = cn.getPackageName();
19031
19032        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
19033                packageName);
19034        if (ivi == null) {
19035            return true;
19036        }
19037        int status = ivi.getStatus();
19038        switch (status) {
19039            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
19040            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
19041                return true;
19042
19043            default:
19044                // Nothing to do
19045                return false;
19046        }
19047    }
19048
19049    private static boolean isMultiArch(ApplicationInfo info) {
19050        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
19051    }
19052
19053    private static boolean isExternal(PackageParser.Package pkg) {
19054        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19055    }
19056
19057    private static boolean isExternal(PackageSetting ps) {
19058        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19059    }
19060
19061    private static boolean isSystemApp(PackageParser.Package pkg) {
19062        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
19063    }
19064
19065    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
19066        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
19067    }
19068
19069    private static boolean hasDomainURLs(PackageParser.Package pkg) {
19070        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
19071    }
19072
19073    private static boolean isSystemApp(PackageSetting ps) {
19074        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
19075    }
19076
19077    private static boolean isUpdatedSystemApp(PackageSetting ps) {
19078        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
19079    }
19080
19081    private int packageFlagsToInstallFlags(PackageSetting ps) {
19082        int installFlags = 0;
19083        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
19084            // This existing package was an external ASEC install when we have
19085            // the external flag without a UUID
19086            installFlags |= PackageManager.INSTALL_EXTERNAL;
19087        }
19088        if (ps.isForwardLocked()) {
19089            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
19090        }
19091        return installFlags;
19092    }
19093
19094    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
19095        if (isExternal(pkg)) {
19096            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19097                return StorageManager.UUID_PRIMARY_PHYSICAL;
19098            } else {
19099                return pkg.volumeUuid;
19100            }
19101        } else {
19102            return StorageManager.UUID_PRIVATE_INTERNAL;
19103        }
19104    }
19105
19106    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
19107        if (isExternal(pkg)) {
19108            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19109                return mSettings.getExternalVersion();
19110            } else {
19111                return mSettings.findOrCreateVersion(pkg.volumeUuid);
19112            }
19113        } else {
19114            return mSettings.getInternalVersion();
19115        }
19116    }
19117
19118    private void deleteTempPackageFiles() {
19119        final FilenameFilter filter = new FilenameFilter() {
19120            public boolean accept(File dir, String name) {
19121                return name.startsWith("vmdl") && name.endsWith(".tmp");
19122            }
19123        };
19124        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
19125            file.delete();
19126        }
19127    }
19128
19129    @Override
19130    public void deletePackageAsUser(String packageName, int versionCode,
19131            IPackageDeleteObserver observer, int userId, int flags) {
19132        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
19133                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
19134    }
19135
19136    @Override
19137    public void deletePackageVersioned(VersionedPackage versionedPackage,
19138            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
19139        final int callingUid = Binder.getCallingUid();
19140        mContext.enforceCallingOrSelfPermission(
19141                android.Manifest.permission.DELETE_PACKAGES, null);
19142        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
19143        Preconditions.checkNotNull(versionedPackage);
19144        Preconditions.checkNotNull(observer);
19145        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
19146                PackageManager.VERSION_CODE_HIGHEST,
19147                Integer.MAX_VALUE, "versionCode must be >= -1");
19148
19149        final String packageName = versionedPackage.getPackageName();
19150        final int versionCode = versionedPackage.getVersionCode();
19151        final String internalPackageName;
19152        synchronized (mPackages) {
19153            // Normalize package name to handle renamed packages and static libs
19154            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19155                    versionedPackage.getVersionCode());
19156        }
19157
19158        final int uid = Binder.getCallingUid();
19159        if (!isOrphaned(internalPackageName)
19160                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19161            try {
19162                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19163                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19164                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19165                observer.onUserActionRequired(intent);
19166            } catch (RemoteException re) {
19167            }
19168            return;
19169        }
19170        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19171        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19172        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19173            mContext.enforceCallingOrSelfPermission(
19174                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19175                    "deletePackage for user " + userId);
19176        }
19177
19178        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19179            try {
19180                observer.onPackageDeleted(packageName,
19181                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19182            } catch (RemoteException re) {
19183            }
19184            return;
19185        }
19186
19187        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19188            try {
19189                observer.onPackageDeleted(packageName,
19190                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19191            } catch (RemoteException re) {
19192            }
19193            return;
19194        }
19195
19196        if (DEBUG_REMOVE) {
19197            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19198                    + " deleteAllUsers: " + deleteAllUsers + " version="
19199                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19200                    ? "VERSION_CODE_HIGHEST" : versionCode));
19201        }
19202        // Queue up an async operation since the package deletion may take a little while.
19203        mHandler.post(new Runnable() {
19204            public void run() {
19205                mHandler.removeCallbacks(this);
19206                int returnCode;
19207                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19208                boolean doDeletePackage = true;
19209                if (ps != null) {
19210                    final boolean targetIsInstantApp =
19211                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19212                    doDeletePackage = !targetIsInstantApp
19213                            || canViewInstantApps;
19214                }
19215                if (doDeletePackage) {
19216                    if (!deleteAllUsers) {
19217                        returnCode = deletePackageX(internalPackageName, versionCode,
19218                                userId, deleteFlags);
19219                    } else {
19220                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19221                                internalPackageName, users);
19222                        // If nobody is blocking uninstall, proceed with delete for all users
19223                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19224                            returnCode = deletePackageX(internalPackageName, versionCode,
19225                                    userId, deleteFlags);
19226                        } else {
19227                            // Otherwise uninstall individually for users with blockUninstalls=false
19228                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19229                            for (int userId : users) {
19230                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19231                                    returnCode = deletePackageX(internalPackageName, versionCode,
19232                                            userId, userFlags);
19233                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19234                                        Slog.w(TAG, "Package delete failed for user " + userId
19235                                                + ", returnCode " + returnCode);
19236                                    }
19237                                }
19238                            }
19239                            // The app has only been marked uninstalled for certain users.
19240                            // We still need to report that delete was blocked
19241                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19242                        }
19243                    }
19244                } else {
19245                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19246                }
19247                try {
19248                    observer.onPackageDeleted(packageName, returnCode, null);
19249                } catch (RemoteException e) {
19250                    Log.i(TAG, "Observer no longer exists.");
19251                } //end catch
19252            } //end run
19253        });
19254    }
19255
19256    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19257        if (pkg.staticSharedLibName != null) {
19258            return pkg.manifestPackageName;
19259        }
19260        return pkg.packageName;
19261    }
19262
19263    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19264        // Handle renamed packages
19265        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19266        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19267
19268        // Is this a static library?
19269        SparseArray<SharedLibraryEntry> versionedLib =
19270                mStaticLibsByDeclaringPackage.get(packageName);
19271        if (versionedLib == null || versionedLib.size() <= 0) {
19272            return packageName;
19273        }
19274
19275        // Figure out which lib versions the caller can see
19276        SparseIntArray versionsCallerCanSee = null;
19277        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19278        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19279                && callingAppId != Process.ROOT_UID) {
19280            versionsCallerCanSee = new SparseIntArray();
19281            String libName = versionedLib.valueAt(0).info.getName();
19282            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19283            if (uidPackages != null) {
19284                for (String uidPackage : uidPackages) {
19285                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19286                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19287                    if (libIdx >= 0) {
19288                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19289                        versionsCallerCanSee.append(libVersion, libVersion);
19290                    }
19291                }
19292            }
19293        }
19294
19295        // Caller can see nothing - done
19296        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19297            return packageName;
19298        }
19299
19300        // Find the version the caller can see and the app version code
19301        SharedLibraryEntry highestVersion = null;
19302        final int versionCount = versionedLib.size();
19303        for (int i = 0; i < versionCount; i++) {
19304            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19305            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19306                    libEntry.info.getVersion()) < 0) {
19307                continue;
19308            }
19309            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19310            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19311                if (libVersionCode == versionCode) {
19312                    return libEntry.apk;
19313                }
19314            } else if (highestVersion == null) {
19315                highestVersion = libEntry;
19316            } else if (libVersionCode  > highestVersion.info
19317                    .getDeclaringPackage().getVersionCode()) {
19318                highestVersion = libEntry;
19319            }
19320        }
19321
19322        if (highestVersion != null) {
19323            return highestVersion.apk;
19324        }
19325
19326        return packageName;
19327    }
19328
19329    boolean isCallerVerifier(int callingUid) {
19330        final int callingUserId = UserHandle.getUserId(callingUid);
19331        return mRequiredVerifierPackage != null &&
19332                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19333    }
19334
19335    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19336        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19337              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19338            return true;
19339        }
19340        final int callingUserId = UserHandle.getUserId(callingUid);
19341        // If the caller installed the pkgName, then allow it to silently uninstall.
19342        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19343            return true;
19344        }
19345
19346        // Allow package verifier to silently uninstall.
19347        if (mRequiredVerifierPackage != null &&
19348                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19349            return true;
19350        }
19351
19352        // Allow package uninstaller to silently uninstall.
19353        if (mRequiredUninstallerPackage != null &&
19354                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19355            return true;
19356        }
19357
19358        // Allow storage manager to silently uninstall.
19359        if (mStorageManagerPackage != null &&
19360                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19361            return true;
19362        }
19363
19364        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19365        // uninstall for device owner provisioning.
19366        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19367                == PERMISSION_GRANTED) {
19368            return true;
19369        }
19370
19371        return false;
19372    }
19373
19374    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19375        int[] result = EMPTY_INT_ARRAY;
19376        for (int userId : userIds) {
19377            if (getBlockUninstallForUser(packageName, userId)) {
19378                result = ArrayUtils.appendInt(result, userId);
19379            }
19380        }
19381        return result;
19382    }
19383
19384    @Override
19385    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19386        final int callingUid = Binder.getCallingUid();
19387        if (getInstantAppPackageName(callingUid) != null
19388                && !isCallerSameApp(packageName, callingUid)) {
19389            return false;
19390        }
19391        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19392    }
19393
19394    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19395        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19396                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19397        try {
19398            if (dpm != null) {
19399                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19400                        /* callingUserOnly =*/ false);
19401                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19402                        : deviceOwnerComponentName.getPackageName();
19403                // Does the package contains the device owner?
19404                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19405                // this check is probably not needed, since DO should be registered as a device
19406                // admin on some user too. (Original bug for this: b/17657954)
19407                if (packageName.equals(deviceOwnerPackageName)) {
19408                    return true;
19409                }
19410                // Does it contain a device admin for any user?
19411                int[] users;
19412                if (userId == UserHandle.USER_ALL) {
19413                    users = sUserManager.getUserIds();
19414                } else {
19415                    users = new int[]{userId};
19416                }
19417                for (int i = 0; i < users.length; ++i) {
19418                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19419                        return true;
19420                    }
19421                }
19422            }
19423        } catch (RemoteException e) {
19424        }
19425        return false;
19426    }
19427
19428    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19429        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19430    }
19431
19432    /**
19433     *  This method is an internal method that could be get invoked either
19434     *  to delete an installed package or to clean up a failed installation.
19435     *  After deleting an installed package, a broadcast is sent to notify any
19436     *  listeners that the package has been removed. For cleaning up a failed
19437     *  installation, the broadcast is not necessary since the package's
19438     *  installation wouldn't have sent the initial broadcast either
19439     *  The key steps in deleting a package are
19440     *  deleting the package information in internal structures like mPackages,
19441     *  deleting the packages base directories through installd
19442     *  updating mSettings to reflect current status
19443     *  persisting settings for later use
19444     *  sending a broadcast if necessary
19445     */
19446    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19447        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19448        final boolean res;
19449
19450        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19451                ? UserHandle.USER_ALL : userId;
19452
19453        if (isPackageDeviceAdmin(packageName, removeUser)) {
19454            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19455            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19456        }
19457
19458        PackageSetting uninstalledPs = null;
19459        PackageParser.Package pkg = null;
19460
19461        // for the uninstall-updates case and restricted profiles, remember the per-
19462        // user handle installed state
19463        int[] allUsers;
19464        synchronized (mPackages) {
19465            uninstalledPs = mSettings.mPackages.get(packageName);
19466            if (uninstalledPs == null) {
19467                Slog.w(TAG, "Not removing non-existent package " + packageName);
19468                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19469            }
19470
19471            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19472                    && uninstalledPs.versionCode != versionCode) {
19473                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19474                        + uninstalledPs.versionCode + " != " + versionCode);
19475                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19476            }
19477
19478            // Static shared libs can be declared by any package, so let us not
19479            // allow removing a package if it provides a lib others depend on.
19480            pkg = mPackages.get(packageName);
19481
19482            allUsers = sUserManager.getUserIds();
19483
19484            if (pkg != null && pkg.staticSharedLibName != null) {
19485                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19486                        pkg.staticSharedLibVersion);
19487                if (libEntry != null) {
19488                    for (int currUserId : allUsers) {
19489                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19490                            continue;
19491                        }
19492                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19493                                libEntry.info, 0, currUserId);
19494                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19495                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19496                                    + " hosting lib " + libEntry.info.getName() + " version "
19497                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19498                                    + " for user " + currUserId);
19499                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19500                        }
19501                    }
19502                }
19503            }
19504
19505            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19506        }
19507
19508        final int freezeUser;
19509        if (isUpdatedSystemApp(uninstalledPs)
19510                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19511            // We're downgrading a system app, which will apply to all users, so
19512            // freeze them all during the downgrade
19513            freezeUser = UserHandle.USER_ALL;
19514        } else {
19515            freezeUser = removeUser;
19516        }
19517
19518        synchronized (mInstallLock) {
19519            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19520            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19521                    deleteFlags, "deletePackageX")) {
19522                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19523                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19524            }
19525            synchronized (mPackages) {
19526                if (res) {
19527                    if (pkg != null) {
19528                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19529                    }
19530                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19531                    updateInstantAppInstallerLocked(packageName);
19532                }
19533            }
19534        }
19535
19536        if (res) {
19537            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19538            info.sendPackageRemovedBroadcasts(killApp);
19539            info.sendSystemPackageUpdatedBroadcasts();
19540            info.sendSystemPackageAppearedBroadcasts();
19541        }
19542        // Force a gc here.
19543        Runtime.getRuntime().gc();
19544        // Delete the resources here after sending the broadcast to let
19545        // other processes clean up before deleting resources.
19546        if (info.args != null) {
19547            synchronized (mInstallLock) {
19548                info.args.doPostDeleteLI(true);
19549            }
19550        }
19551
19552        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19553    }
19554
19555    static class PackageRemovedInfo {
19556        final PackageSender packageSender;
19557        String removedPackage;
19558        String installerPackageName;
19559        int uid = -1;
19560        int removedAppId = -1;
19561        int[] origUsers;
19562        int[] removedUsers = null;
19563        int[] broadcastUsers = null;
19564        SparseArray<Integer> installReasons;
19565        boolean isRemovedPackageSystemUpdate = false;
19566        boolean isUpdate;
19567        boolean dataRemoved;
19568        boolean removedForAllUsers;
19569        boolean isStaticSharedLib;
19570        // Clean up resources deleted packages.
19571        InstallArgs args = null;
19572        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19573        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19574
19575        PackageRemovedInfo(PackageSender packageSender) {
19576            this.packageSender = packageSender;
19577        }
19578
19579        void sendPackageRemovedBroadcasts(boolean killApp) {
19580            sendPackageRemovedBroadcastInternal(killApp);
19581            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19582            for (int i = 0; i < childCount; i++) {
19583                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19584                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19585            }
19586        }
19587
19588        void sendSystemPackageUpdatedBroadcasts() {
19589            if (isRemovedPackageSystemUpdate) {
19590                sendSystemPackageUpdatedBroadcastsInternal();
19591                final int childCount = (removedChildPackages != null)
19592                        ? removedChildPackages.size() : 0;
19593                for (int i = 0; i < childCount; i++) {
19594                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19595                    if (childInfo.isRemovedPackageSystemUpdate) {
19596                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19597                    }
19598                }
19599            }
19600        }
19601
19602        void sendSystemPackageAppearedBroadcasts() {
19603            final int packageCount = (appearedChildPackages != null)
19604                    ? appearedChildPackages.size() : 0;
19605            for (int i = 0; i < packageCount; i++) {
19606                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19607                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19608                    true /*sendBootCompleted*/, false /*startReceiver*/,
19609                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19610            }
19611        }
19612
19613        private void sendSystemPackageUpdatedBroadcastsInternal() {
19614            Bundle extras = new Bundle(2);
19615            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19616            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19617            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19618                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19619            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19620                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19621            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19622                null, null, 0, removedPackage, null, null);
19623            if (installerPackageName != null) {
19624                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19625                        removedPackage, extras, 0 /*flags*/,
19626                        installerPackageName, null, null);
19627                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19628                        removedPackage, extras, 0 /*flags*/,
19629                        installerPackageName, null, null);
19630            }
19631        }
19632
19633        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19634            // Don't send static shared library removal broadcasts as these
19635            // libs are visible only the the apps that depend on them an one
19636            // cannot remove the library if it has a dependency.
19637            if (isStaticSharedLib) {
19638                return;
19639            }
19640            Bundle extras = new Bundle(2);
19641            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19642            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19643            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19644            if (isUpdate || isRemovedPackageSystemUpdate) {
19645                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19646            }
19647            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19648            if (removedPackage != null) {
19649                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19650                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19651                if (installerPackageName != null) {
19652                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19653                            removedPackage, extras, 0 /*flags*/,
19654                            installerPackageName, null, broadcastUsers);
19655                }
19656                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19657                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19658                        removedPackage, extras,
19659                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19660                        null, null, broadcastUsers);
19661                }
19662            }
19663            if (removedAppId >= 0) {
19664                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19665                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19666                    null, null, broadcastUsers);
19667            }
19668        }
19669
19670        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19671            removedUsers = userIds;
19672            if (removedUsers == null) {
19673                broadcastUsers = null;
19674                return;
19675            }
19676
19677            broadcastUsers = EMPTY_INT_ARRAY;
19678            for (int i = userIds.length - 1; i >= 0; --i) {
19679                final int userId = userIds[i];
19680                if (deletedPackageSetting.getInstantApp(userId)) {
19681                    continue;
19682                }
19683                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19684            }
19685        }
19686    }
19687
19688    /*
19689     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19690     * flag is not set, the data directory is removed as well.
19691     * make sure this flag is set for partially installed apps. If not its meaningless to
19692     * delete a partially installed application.
19693     */
19694    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19695            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19696        String packageName = ps.name;
19697        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19698        // Retrieve object to delete permissions for shared user later on
19699        final PackageParser.Package deletedPkg;
19700        final PackageSetting deletedPs;
19701        // reader
19702        synchronized (mPackages) {
19703            deletedPkg = mPackages.get(packageName);
19704            deletedPs = mSettings.mPackages.get(packageName);
19705            if (outInfo != null) {
19706                outInfo.removedPackage = packageName;
19707                outInfo.installerPackageName = ps.installerPackageName;
19708                outInfo.isStaticSharedLib = deletedPkg != null
19709                        && deletedPkg.staticSharedLibName != null;
19710                outInfo.populateUsers(deletedPs == null ? null
19711                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19712            }
19713        }
19714
19715        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19716
19717        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19718            final PackageParser.Package resolvedPkg;
19719            if (deletedPkg != null) {
19720                resolvedPkg = deletedPkg;
19721            } else {
19722                // We don't have a parsed package when it lives on an ejected
19723                // adopted storage device, so fake something together
19724                resolvedPkg = new PackageParser.Package(ps.name);
19725                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19726            }
19727            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19728                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19729            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19730            if (outInfo != null) {
19731                outInfo.dataRemoved = true;
19732            }
19733            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19734        }
19735
19736        int removedAppId = -1;
19737
19738        // writer
19739        synchronized (mPackages) {
19740            boolean installedStateChanged = false;
19741            if (deletedPs != null) {
19742                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19743                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19744                    clearDefaultBrowserIfNeeded(packageName);
19745                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19746                    removedAppId = mSettings.removePackageLPw(packageName);
19747                    if (outInfo != null) {
19748                        outInfo.removedAppId = removedAppId;
19749                    }
19750                    updatePermissionsLPw(deletedPs.name, null, 0);
19751                    if (deletedPs.sharedUser != null) {
19752                        // Remove permissions associated with package. Since runtime
19753                        // permissions are per user we have to kill the removed package
19754                        // or packages running under the shared user of the removed
19755                        // package if revoking the permissions requested only by the removed
19756                        // package is successful and this causes a change in gids.
19757                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19758                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19759                                    userId);
19760                            if (userIdToKill == UserHandle.USER_ALL
19761                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19762                                // If gids changed for this user, kill all affected packages.
19763                                mHandler.post(new Runnable() {
19764                                    @Override
19765                                    public void run() {
19766                                        // This has to happen with no lock held.
19767                                        killApplication(deletedPs.name, deletedPs.appId,
19768                                                KILL_APP_REASON_GIDS_CHANGED);
19769                                    }
19770                                });
19771                                break;
19772                            }
19773                        }
19774                    }
19775                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19776                }
19777                // make sure to preserve per-user disabled state if this removal was just
19778                // a downgrade of a system app to the factory package
19779                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19780                    if (DEBUG_REMOVE) {
19781                        Slog.d(TAG, "Propagating install state across downgrade");
19782                    }
19783                    for (int userId : allUserHandles) {
19784                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19785                        if (DEBUG_REMOVE) {
19786                            Slog.d(TAG, "    user " + userId + " => " + installed);
19787                        }
19788                        if (installed != ps.getInstalled(userId)) {
19789                            installedStateChanged = true;
19790                        }
19791                        ps.setInstalled(installed, userId);
19792                    }
19793                }
19794            }
19795            // can downgrade to reader
19796            if (writeSettings) {
19797                // Save settings now
19798                mSettings.writeLPr();
19799            }
19800            if (installedStateChanged) {
19801                mSettings.writeKernelMappingLPr(ps);
19802            }
19803        }
19804        if (removedAppId != -1) {
19805            // A user ID was deleted here. Go through all users and remove it
19806            // from KeyStore.
19807            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19808        }
19809    }
19810
19811    static boolean locationIsPrivileged(File path) {
19812        try {
19813            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19814                    .getCanonicalPath();
19815            return path.getCanonicalPath().startsWith(privilegedAppDir);
19816        } catch (IOException e) {
19817            Slog.e(TAG, "Unable to access code path " + path);
19818        }
19819        return false;
19820    }
19821
19822    /*
19823     * Tries to delete system package.
19824     */
19825    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19826            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19827            boolean writeSettings) {
19828        if (deletedPs.parentPackageName != null) {
19829            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19830            return false;
19831        }
19832
19833        final boolean applyUserRestrictions
19834                = (allUserHandles != null) && (outInfo.origUsers != null);
19835        final PackageSetting disabledPs;
19836        // Confirm if the system package has been updated
19837        // An updated system app can be deleted. This will also have to restore
19838        // the system pkg from system partition
19839        // reader
19840        synchronized (mPackages) {
19841            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19842        }
19843
19844        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19845                + " disabledPs=" + disabledPs);
19846
19847        if (disabledPs == null) {
19848            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19849            return false;
19850        } else if (DEBUG_REMOVE) {
19851            Slog.d(TAG, "Deleting system pkg from data partition");
19852        }
19853
19854        if (DEBUG_REMOVE) {
19855            if (applyUserRestrictions) {
19856                Slog.d(TAG, "Remembering install states:");
19857                for (int userId : allUserHandles) {
19858                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19859                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19860                }
19861            }
19862        }
19863
19864        // Delete the updated package
19865        outInfo.isRemovedPackageSystemUpdate = true;
19866        if (outInfo.removedChildPackages != null) {
19867            final int childCount = (deletedPs.childPackageNames != null)
19868                    ? deletedPs.childPackageNames.size() : 0;
19869            for (int i = 0; i < childCount; i++) {
19870                String childPackageName = deletedPs.childPackageNames.get(i);
19871                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19872                        .contains(childPackageName)) {
19873                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19874                            childPackageName);
19875                    if (childInfo != null) {
19876                        childInfo.isRemovedPackageSystemUpdate = true;
19877                    }
19878                }
19879            }
19880        }
19881
19882        if (disabledPs.versionCode < deletedPs.versionCode) {
19883            // Delete data for downgrades
19884            flags &= ~PackageManager.DELETE_KEEP_DATA;
19885        } else {
19886            // Preserve data by setting flag
19887            flags |= PackageManager.DELETE_KEEP_DATA;
19888        }
19889
19890        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19891                outInfo, writeSettings, disabledPs.pkg);
19892        if (!ret) {
19893            return false;
19894        }
19895
19896        // writer
19897        synchronized (mPackages) {
19898            // NOTE: The system package always needs to be enabled; even if it's for
19899            // a compressed stub. If we don't, installing the system package fails
19900            // during scan [scanning checks the disabled packages]. We will reverse
19901            // this later, after we've "installed" the stub.
19902            // Reinstate the old system package
19903            enableSystemPackageLPw(disabledPs.pkg);
19904            // Remove any native libraries from the upgraded package.
19905            removeNativeBinariesLI(deletedPs);
19906        }
19907
19908        // Install the system package
19909        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19910        try {
19911            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19912                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19913        } catch (PackageManagerException e) {
19914            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19915                    + e.getMessage());
19916            return false;
19917        } finally {
19918            if (disabledPs.pkg.isStub) {
19919                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19920            }
19921        }
19922        return true;
19923    }
19924
19925    /**
19926     * Installs a package that's already on the system partition.
19927     */
19928    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19929            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19930            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19931                    throws PackageManagerException {
19932        int parseFlags = mDefParseFlags
19933                | PackageParser.PARSE_MUST_BE_APK
19934                | PackageParser.PARSE_IS_SYSTEM
19935                | PackageParser.PARSE_IS_SYSTEM_DIR;
19936        if (isPrivileged || locationIsPrivileged(codePath)) {
19937            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19938        }
19939
19940        final PackageParser.Package newPkg =
19941                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19942
19943        try {
19944            // update shared libraries for the newly re-installed system package
19945            updateSharedLibrariesLPr(newPkg, null);
19946        } catch (PackageManagerException e) {
19947            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19948        }
19949
19950        prepareAppDataAfterInstallLIF(newPkg);
19951
19952        // writer
19953        synchronized (mPackages) {
19954            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19955
19956            // Propagate the permissions state as we do not want to drop on the floor
19957            // runtime permissions. The update permissions method below will take
19958            // care of removing obsolete permissions and grant install permissions.
19959            if (origPermissionState != null) {
19960                ps.getPermissionsState().copyFrom(origPermissionState);
19961            }
19962            updatePermissionsLPw(newPkg.packageName, newPkg,
19963                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19964
19965            final boolean applyUserRestrictions
19966                    = (allUserHandles != null) && (origUserHandles != null);
19967            if (applyUserRestrictions) {
19968                boolean installedStateChanged = false;
19969                if (DEBUG_REMOVE) {
19970                    Slog.d(TAG, "Propagating install state across reinstall");
19971                }
19972                for (int userId : allUserHandles) {
19973                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19974                    if (DEBUG_REMOVE) {
19975                        Slog.d(TAG, "    user " + userId + " => " + installed);
19976                    }
19977                    if (installed != ps.getInstalled(userId)) {
19978                        installedStateChanged = true;
19979                    }
19980                    ps.setInstalled(installed, userId);
19981
19982                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19983                }
19984                // Regardless of writeSettings we need to ensure that this restriction
19985                // state propagation is persisted
19986                mSettings.writeAllUsersPackageRestrictionsLPr();
19987                if (installedStateChanged) {
19988                    mSettings.writeKernelMappingLPr(ps);
19989                }
19990            }
19991            // can downgrade to reader here
19992            if (writeSettings) {
19993                mSettings.writeLPr();
19994            }
19995        }
19996        return newPkg;
19997    }
19998
19999    private boolean deleteInstalledPackageLIF(PackageSetting ps,
20000            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
20001            PackageRemovedInfo outInfo, boolean writeSettings,
20002            PackageParser.Package replacingPackage) {
20003        synchronized (mPackages) {
20004            if (outInfo != null) {
20005                outInfo.uid = ps.appId;
20006            }
20007
20008            if (outInfo != null && outInfo.removedChildPackages != null) {
20009                final int childCount = (ps.childPackageNames != null)
20010                        ? ps.childPackageNames.size() : 0;
20011                for (int i = 0; i < childCount; i++) {
20012                    String childPackageName = ps.childPackageNames.get(i);
20013                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
20014                    if (childPs == null) {
20015                        return false;
20016                    }
20017                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
20018                            childPackageName);
20019                    if (childInfo != null) {
20020                        childInfo.uid = childPs.appId;
20021                    }
20022                }
20023            }
20024        }
20025
20026        // Delete package data from internal structures and also remove data if flag is set
20027        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
20028
20029        // Delete the child packages data
20030        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
20031        for (int i = 0; i < childCount; i++) {
20032            PackageSetting childPs;
20033            synchronized (mPackages) {
20034                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
20035            }
20036            if (childPs != null) {
20037                PackageRemovedInfo childOutInfo = (outInfo != null
20038                        && outInfo.removedChildPackages != null)
20039                        ? outInfo.removedChildPackages.get(childPs.name) : null;
20040                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
20041                        && (replacingPackage != null
20042                        && !replacingPackage.hasChildPackage(childPs.name))
20043                        ? flags & ~DELETE_KEEP_DATA : flags;
20044                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
20045                        deleteFlags, writeSettings);
20046            }
20047        }
20048
20049        // Delete application code and resources only for parent packages
20050        if (ps.parentPackageName == null) {
20051            if (deleteCodeAndResources && (outInfo != null)) {
20052                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
20053                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
20054                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
20055            }
20056        }
20057
20058        return true;
20059    }
20060
20061    @Override
20062    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
20063            int userId) {
20064        mContext.enforceCallingOrSelfPermission(
20065                android.Manifest.permission.DELETE_PACKAGES, null);
20066        synchronized (mPackages) {
20067            // Cannot block uninstall of static shared libs as they are
20068            // considered a part of the using app (emulating static linking).
20069            // Also static libs are installed always on internal storage.
20070            PackageParser.Package pkg = mPackages.get(packageName);
20071            if (pkg != null && pkg.staticSharedLibName != null) {
20072                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
20073                        + " providing static shared library: " + pkg.staticSharedLibName);
20074                return false;
20075            }
20076            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
20077            mSettings.writePackageRestrictionsLPr(userId);
20078        }
20079        return true;
20080    }
20081
20082    @Override
20083    public boolean getBlockUninstallForUser(String packageName, int userId) {
20084        synchronized (mPackages) {
20085            final PackageSetting ps = mSettings.mPackages.get(packageName);
20086            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
20087                return false;
20088            }
20089            return mSettings.getBlockUninstallLPr(userId, packageName);
20090        }
20091    }
20092
20093    @Override
20094    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
20095        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
20096        synchronized (mPackages) {
20097            PackageSetting ps = mSettings.mPackages.get(packageName);
20098            if (ps == null) {
20099                Log.w(TAG, "Package doesn't exist: " + packageName);
20100                return false;
20101            }
20102            if (systemUserApp) {
20103                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20104            } else {
20105                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20106            }
20107            mSettings.writeLPr();
20108        }
20109        return true;
20110    }
20111
20112    /*
20113     * This method handles package deletion in general
20114     */
20115    private boolean deletePackageLIF(String packageName, UserHandle user,
20116            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
20117            PackageRemovedInfo outInfo, boolean writeSettings,
20118            PackageParser.Package replacingPackage) {
20119        if (packageName == null) {
20120            Slog.w(TAG, "Attempt to delete null packageName.");
20121            return false;
20122        }
20123
20124        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
20125
20126        PackageSetting ps;
20127        synchronized (mPackages) {
20128            ps = mSettings.mPackages.get(packageName);
20129            if (ps == null) {
20130                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20131                return false;
20132            }
20133
20134            if (ps.parentPackageName != null && (!isSystemApp(ps)
20135                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
20136                if (DEBUG_REMOVE) {
20137                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
20138                            + ((user == null) ? UserHandle.USER_ALL : user));
20139                }
20140                final int removedUserId = (user != null) ? user.getIdentifier()
20141                        : UserHandle.USER_ALL;
20142                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
20143                    return false;
20144                }
20145                markPackageUninstalledForUserLPw(ps, user);
20146                scheduleWritePackageRestrictionsLocked(user);
20147                return true;
20148            }
20149        }
20150
20151        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
20152                && user.getIdentifier() != UserHandle.USER_ALL)) {
20153            // The caller is asking that the package only be deleted for a single
20154            // user.  To do this, we just mark its uninstalled state and delete
20155            // its data. If this is a system app, we only allow this to happen if
20156            // they have set the special DELETE_SYSTEM_APP which requests different
20157            // semantics than normal for uninstalling system apps.
20158            markPackageUninstalledForUserLPw(ps, user);
20159
20160            if (!isSystemApp(ps)) {
20161                // Do not uninstall the APK if an app should be cached
20162                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
20163                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
20164                    // Other user still have this package installed, so all
20165                    // we need to do is clear this user's data and save that
20166                    // it is uninstalled.
20167                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
20168                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20169                        return false;
20170                    }
20171                    scheduleWritePackageRestrictionsLocked(user);
20172                    return true;
20173                } else {
20174                    // We need to set it back to 'installed' so the uninstall
20175                    // broadcasts will be sent correctly.
20176                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20177                    ps.setInstalled(true, user.getIdentifier());
20178                    mSettings.writeKernelMappingLPr(ps);
20179                }
20180            } else {
20181                // This is a system app, so we assume that the
20182                // other users still have this package installed, so all
20183                // we need to do is clear this user's data and save that
20184                // it is uninstalled.
20185                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20186                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20187                    return false;
20188                }
20189                scheduleWritePackageRestrictionsLocked(user);
20190                return true;
20191            }
20192        }
20193
20194        // If we are deleting a composite package for all users, keep track
20195        // of result for each child.
20196        if (ps.childPackageNames != null && outInfo != null) {
20197            synchronized (mPackages) {
20198                final int childCount = ps.childPackageNames.size();
20199                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20200                for (int i = 0; i < childCount; i++) {
20201                    String childPackageName = ps.childPackageNames.get(i);
20202                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20203                    childInfo.removedPackage = childPackageName;
20204                    childInfo.installerPackageName = ps.installerPackageName;
20205                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20206                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20207                    if (childPs != null) {
20208                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20209                    }
20210                }
20211            }
20212        }
20213
20214        boolean ret = false;
20215        if (isSystemApp(ps)) {
20216            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20217            // When an updated system application is deleted we delete the existing resources
20218            // as well and fall back to existing code in system partition
20219            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20220        } else {
20221            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20222            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20223                    outInfo, writeSettings, replacingPackage);
20224        }
20225
20226        // Take a note whether we deleted the package for all users
20227        if (outInfo != null) {
20228            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20229            if (outInfo.removedChildPackages != null) {
20230                synchronized (mPackages) {
20231                    final int childCount = outInfo.removedChildPackages.size();
20232                    for (int i = 0; i < childCount; i++) {
20233                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20234                        if (childInfo != null) {
20235                            childInfo.removedForAllUsers = mPackages.get(
20236                                    childInfo.removedPackage) == null;
20237                        }
20238                    }
20239                }
20240            }
20241            // If we uninstalled an update to a system app there may be some
20242            // child packages that appeared as they are declared in the system
20243            // app but were not declared in the update.
20244            if (isSystemApp(ps)) {
20245                synchronized (mPackages) {
20246                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20247                    final int childCount = (updatedPs.childPackageNames != null)
20248                            ? updatedPs.childPackageNames.size() : 0;
20249                    for (int i = 0; i < childCount; i++) {
20250                        String childPackageName = updatedPs.childPackageNames.get(i);
20251                        if (outInfo.removedChildPackages == null
20252                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20253                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20254                            if (childPs == null) {
20255                                continue;
20256                            }
20257                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20258                            installRes.name = childPackageName;
20259                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20260                            installRes.pkg = mPackages.get(childPackageName);
20261                            installRes.uid = childPs.pkg.applicationInfo.uid;
20262                            if (outInfo.appearedChildPackages == null) {
20263                                outInfo.appearedChildPackages = new ArrayMap<>();
20264                            }
20265                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20266                        }
20267                    }
20268                }
20269            }
20270        }
20271
20272        return ret;
20273    }
20274
20275    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20276        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20277                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20278        for (int nextUserId : userIds) {
20279            if (DEBUG_REMOVE) {
20280                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20281            }
20282            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20283                    false /*installed*/,
20284                    true /*stopped*/,
20285                    true /*notLaunched*/,
20286                    false /*hidden*/,
20287                    false /*suspended*/,
20288                    false /*instantApp*/,
20289                    false /*virtualPreload*/,
20290                    null /*lastDisableAppCaller*/,
20291                    null /*enabledComponents*/,
20292                    null /*disabledComponents*/,
20293                    ps.readUserState(nextUserId).domainVerificationStatus,
20294                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20295        }
20296        mSettings.writeKernelMappingLPr(ps);
20297    }
20298
20299    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20300            PackageRemovedInfo outInfo) {
20301        final PackageParser.Package pkg;
20302        synchronized (mPackages) {
20303            pkg = mPackages.get(ps.name);
20304        }
20305
20306        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20307                : new int[] {userId};
20308        for (int nextUserId : userIds) {
20309            if (DEBUG_REMOVE) {
20310                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20311                        + nextUserId);
20312            }
20313
20314            destroyAppDataLIF(pkg, userId,
20315                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20316            destroyAppProfilesLIF(pkg, userId);
20317            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20318            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20319            schedulePackageCleaning(ps.name, nextUserId, false);
20320            synchronized (mPackages) {
20321                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20322                    scheduleWritePackageRestrictionsLocked(nextUserId);
20323                }
20324                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20325            }
20326        }
20327
20328        if (outInfo != null) {
20329            outInfo.removedPackage = ps.name;
20330            outInfo.installerPackageName = ps.installerPackageName;
20331            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20332            outInfo.removedAppId = ps.appId;
20333            outInfo.removedUsers = userIds;
20334            outInfo.broadcastUsers = userIds;
20335        }
20336
20337        return true;
20338    }
20339
20340    private final class ClearStorageConnection implements ServiceConnection {
20341        IMediaContainerService mContainerService;
20342
20343        @Override
20344        public void onServiceConnected(ComponentName name, IBinder service) {
20345            synchronized (this) {
20346                mContainerService = IMediaContainerService.Stub
20347                        .asInterface(Binder.allowBlocking(service));
20348                notifyAll();
20349            }
20350        }
20351
20352        @Override
20353        public void onServiceDisconnected(ComponentName name) {
20354        }
20355    }
20356
20357    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20358        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20359
20360        final boolean mounted;
20361        if (Environment.isExternalStorageEmulated()) {
20362            mounted = true;
20363        } else {
20364            final String status = Environment.getExternalStorageState();
20365
20366            mounted = status.equals(Environment.MEDIA_MOUNTED)
20367                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20368        }
20369
20370        if (!mounted) {
20371            return;
20372        }
20373
20374        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20375        int[] users;
20376        if (userId == UserHandle.USER_ALL) {
20377            users = sUserManager.getUserIds();
20378        } else {
20379            users = new int[] { userId };
20380        }
20381        final ClearStorageConnection conn = new ClearStorageConnection();
20382        if (mContext.bindServiceAsUser(
20383                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20384            try {
20385                for (int curUser : users) {
20386                    long timeout = SystemClock.uptimeMillis() + 5000;
20387                    synchronized (conn) {
20388                        long now;
20389                        while (conn.mContainerService == null &&
20390                                (now = SystemClock.uptimeMillis()) < timeout) {
20391                            try {
20392                                conn.wait(timeout - now);
20393                            } catch (InterruptedException e) {
20394                            }
20395                        }
20396                    }
20397                    if (conn.mContainerService == null) {
20398                        return;
20399                    }
20400
20401                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20402                    clearDirectory(conn.mContainerService,
20403                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20404                    if (allData) {
20405                        clearDirectory(conn.mContainerService,
20406                                userEnv.buildExternalStorageAppDataDirs(packageName));
20407                        clearDirectory(conn.mContainerService,
20408                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20409                    }
20410                }
20411            } finally {
20412                mContext.unbindService(conn);
20413            }
20414        }
20415    }
20416
20417    @Override
20418    public void clearApplicationProfileData(String packageName) {
20419        enforceSystemOrRoot("Only the system can clear all profile data");
20420
20421        final PackageParser.Package pkg;
20422        synchronized (mPackages) {
20423            pkg = mPackages.get(packageName);
20424        }
20425
20426        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20427            synchronized (mInstallLock) {
20428                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20429            }
20430        }
20431    }
20432
20433    @Override
20434    public void clearApplicationUserData(final String packageName,
20435            final IPackageDataObserver observer, final int userId) {
20436        mContext.enforceCallingOrSelfPermission(
20437                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20438
20439        final int callingUid = Binder.getCallingUid();
20440        enforceCrossUserPermission(callingUid, userId,
20441                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20442
20443        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20444        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20445        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20446            throw new SecurityException("Cannot clear data for a protected package: "
20447                    + packageName);
20448        }
20449        // Queue up an async operation since the package deletion may take a little while.
20450        mHandler.post(new Runnable() {
20451            public void run() {
20452                mHandler.removeCallbacks(this);
20453                final boolean succeeded;
20454                if (!filterApp) {
20455                    try (PackageFreezer freezer = freezePackage(packageName,
20456                            "clearApplicationUserData")) {
20457                        synchronized (mInstallLock) {
20458                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20459                        }
20460                        clearExternalStorageDataSync(packageName, userId, true);
20461                        synchronized (mPackages) {
20462                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20463                                    packageName, userId);
20464                        }
20465                    }
20466                    if (succeeded) {
20467                        // invoke DeviceStorageMonitor's update method to clear any notifications
20468                        DeviceStorageMonitorInternal dsm = LocalServices
20469                                .getService(DeviceStorageMonitorInternal.class);
20470                        if (dsm != null) {
20471                            dsm.checkMemory();
20472                        }
20473                    }
20474                } else {
20475                    succeeded = false;
20476                }
20477                if (observer != null) {
20478                    try {
20479                        observer.onRemoveCompleted(packageName, succeeded);
20480                    } catch (RemoteException e) {
20481                        Log.i(TAG, "Observer no longer exists.");
20482                    }
20483                } //end if observer
20484            } //end run
20485        });
20486    }
20487
20488    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20489        if (packageName == null) {
20490            Slog.w(TAG, "Attempt to delete null packageName.");
20491            return false;
20492        }
20493
20494        // Try finding details about the requested package
20495        PackageParser.Package pkg;
20496        synchronized (mPackages) {
20497            pkg = mPackages.get(packageName);
20498            if (pkg == null) {
20499                final PackageSetting ps = mSettings.mPackages.get(packageName);
20500                if (ps != null) {
20501                    pkg = ps.pkg;
20502                }
20503            }
20504
20505            if (pkg == null) {
20506                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20507                return false;
20508            }
20509
20510            PackageSetting ps = (PackageSetting) pkg.mExtras;
20511            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20512        }
20513
20514        clearAppDataLIF(pkg, userId,
20515                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20516
20517        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20518        removeKeystoreDataIfNeeded(userId, appId);
20519
20520        UserManagerInternal umInternal = getUserManagerInternal();
20521        final int flags;
20522        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20523            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20524        } else if (umInternal.isUserRunning(userId)) {
20525            flags = StorageManager.FLAG_STORAGE_DE;
20526        } else {
20527            flags = 0;
20528        }
20529        prepareAppDataContentsLIF(pkg, userId, flags);
20530
20531        return true;
20532    }
20533
20534    /**
20535     * Reverts user permission state changes (permissions and flags) in
20536     * all packages for a given user.
20537     *
20538     * @param userId The device user for which to do a reset.
20539     */
20540    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20541        final int packageCount = mPackages.size();
20542        for (int i = 0; i < packageCount; i++) {
20543            PackageParser.Package pkg = mPackages.valueAt(i);
20544            PackageSetting ps = (PackageSetting) pkg.mExtras;
20545            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20546        }
20547    }
20548
20549    private void resetNetworkPolicies(int userId) {
20550        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20551    }
20552
20553    /**
20554     * Reverts user permission state changes (permissions and flags).
20555     *
20556     * @param ps The package for which to reset.
20557     * @param userId The device user for which to do a reset.
20558     */
20559    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20560            final PackageSetting ps, final int userId) {
20561        if (ps.pkg == null) {
20562            return;
20563        }
20564
20565        // These are flags that can change base on user actions.
20566        final int userSettableMask = FLAG_PERMISSION_USER_SET
20567                | FLAG_PERMISSION_USER_FIXED
20568                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20569                | FLAG_PERMISSION_REVIEW_REQUIRED;
20570
20571        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20572                | FLAG_PERMISSION_POLICY_FIXED;
20573
20574        boolean writeInstallPermissions = false;
20575        boolean writeRuntimePermissions = false;
20576
20577        final int permissionCount = ps.pkg.requestedPermissions.size();
20578        for (int i = 0; i < permissionCount; i++) {
20579            String permission = ps.pkg.requestedPermissions.get(i);
20580
20581            BasePermission bp = mSettings.mPermissions.get(permission);
20582            if (bp == null) {
20583                continue;
20584            }
20585
20586            // If shared user we just reset the state to which only this app contributed.
20587            if (ps.sharedUser != null) {
20588                boolean used = false;
20589                final int packageCount = ps.sharedUser.packages.size();
20590                for (int j = 0; j < packageCount; j++) {
20591                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20592                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20593                            && pkg.pkg.requestedPermissions.contains(permission)) {
20594                        used = true;
20595                        break;
20596                    }
20597                }
20598                if (used) {
20599                    continue;
20600                }
20601            }
20602
20603            PermissionsState permissionsState = ps.getPermissionsState();
20604
20605            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20606
20607            // Always clear the user settable flags.
20608            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20609                    bp.name) != null;
20610            // If permission review is enabled and this is a legacy app, mark the
20611            // permission as requiring a review as this is the initial state.
20612            int flags = 0;
20613            if (mPermissionReviewRequired
20614                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20615                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20616            }
20617            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20618                if (hasInstallState) {
20619                    writeInstallPermissions = true;
20620                } else {
20621                    writeRuntimePermissions = true;
20622                }
20623            }
20624
20625            // Below is only runtime permission handling.
20626            if (!bp.isRuntime()) {
20627                continue;
20628            }
20629
20630            // Never clobber system or policy.
20631            if ((oldFlags & policyOrSystemFlags) != 0) {
20632                continue;
20633            }
20634
20635            // If this permission was granted by default, make sure it is.
20636            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20637                if (permissionsState.grantRuntimePermission(bp, userId)
20638                        != PERMISSION_OPERATION_FAILURE) {
20639                    writeRuntimePermissions = true;
20640                }
20641            // If permission review is enabled the permissions for a legacy apps
20642            // are represented as constantly granted runtime ones, so don't revoke.
20643            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20644                // Otherwise, reset the permission.
20645                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20646                switch (revokeResult) {
20647                    case PERMISSION_OPERATION_SUCCESS:
20648                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20649                        writeRuntimePermissions = true;
20650                        final int appId = ps.appId;
20651                        mHandler.post(new Runnable() {
20652                            @Override
20653                            public void run() {
20654                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20655                            }
20656                        });
20657                    } break;
20658                }
20659            }
20660        }
20661
20662        // Synchronously write as we are taking permissions away.
20663        if (writeRuntimePermissions) {
20664            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20665        }
20666
20667        // Synchronously write as we are taking permissions away.
20668        if (writeInstallPermissions) {
20669            mSettings.writeLPr();
20670        }
20671    }
20672
20673    /**
20674     * Remove entries from the keystore daemon. Will only remove it if the
20675     * {@code appId} is valid.
20676     */
20677    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20678        if (appId < 0) {
20679            return;
20680        }
20681
20682        final KeyStore keyStore = KeyStore.getInstance();
20683        if (keyStore != null) {
20684            if (userId == UserHandle.USER_ALL) {
20685                for (final int individual : sUserManager.getUserIds()) {
20686                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20687                }
20688            } else {
20689                keyStore.clearUid(UserHandle.getUid(userId, appId));
20690            }
20691        } else {
20692            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20693        }
20694    }
20695
20696    @Override
20697    public void deleteApplicationCacheFiles(final String packageName,
20698            final IPackageDataObserver observer) {
20699        final int userId = UserHandle.getCallingUserId();
20700        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20701    }
20702
20703    @Override
20704    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20705            final IPackageDataObserver observer) {
20706        final int callingUid = Binder.getCallingUid();
20707        mContext.enforceCallingOrSelfPermission(
20708                android.Manifest.permission.DELETE_CACHE_FILES, null);
20709        enforceCrossUserPermission(callingUid, userId,
20710                /* requireFullPermission= */ true, /* checkShell= */ false,
20711                "delete application cache files");
20712        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20713                android.Manifest.permission.ACCESS_INSTANT_APPS);
20714
20715        final PackageParser.Package pkg;
20716        synchronized (mPackages) {
20717            pkg = mPackages.get(packageName);
20718        }
20719
20720        // Queue up an async operation since the package deletion may take a little while.
20721        mHandler.post(new Runnable() {
20722            public void run() {
20723                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20724                boolean doClearData = true;
20725                if (ps != null) {
20726                    final boolean targetIsInstantApp =
20727                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20728                    doClearData = !targetIsInstantApp
20729                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20730                }
20731                if (doClearData) {
20732                    synchronized (mInstallLock) {
20733                        final int flags = StorageManager.FLAG_STORAGE_DE
20734                                | StorageManager.FLAG_STORAGE_CE;
20735                        // We're only clearing cache files, so we don't care if the
20736                        // app is unfrozen and still able to run
20737                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20738                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20739                    }
20740                    clearExternalStorageDataSync(packageName, userId, false);
20741                }
20742                if (observer != null) {
20743                    try {
20744                        observer.onRemoveCompleted(packageName, true);
20745                    } catch (RemoteException e) {
20746                        Log.i(TAG, "Observer no longer exists.");
20747                    }
20748                }
20749            }
20750        });
20751    }
20752
20753    @Override
20754    public void getPackageSizeInfo(final String packageName, int userHandle,
20755            final IPackageStatsObserver observer) {
20756        throw new UnsupportedOperationException(
20757                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20758    }
20759
20760    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20761        final PackageSetting ps;
20762        synchronized (mPackages) {
20763            ps = mSettings.mPackages.get(packageName);
20764            if (ps == null) {
20765                Slog.w(TAG, "Failed to find settings for " + packageName);
20766                return false;
20767            }
20768        }
20769
20770        final String[] packageNames = { packageName };
20771        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20772        final String[] codePaths = { ps.codePathString };
20773
20774        try {
20775            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20776                    ps.appId, ceDataInodes, codePaths, stats);
20777
20778            // For now, ignore code size of packages on system partition
20779            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20780                stats.codeSize = 0;
20781            }
20782
20783            // External clients expect these to be tracked separately
20784            stats.dataSize -= stats.cacheSize;
20785
20786        } catch (InstallerException e) {
20787            Slog.w(TAG, String.valueOf(e));
20788            return false;
20789        }
20790
20791        return true;
20792    }
20793
20794    private int getUidTargetSdkVersionLockedLPr(int uid) {
20795        Object obj = mSettings.getUserIdLPr(uid);
20796        if (obj instanceof SharedUserSetting) {
20797            final SharedUserSetting sus = (SharedUserSetting) obj;
20798            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20799            final Iterator<PackageSetting> it = sus.packages.iterator();
20800            while (it.hasNext()) {
20801                final PackageSetting ps = it.next();
20802                if (ps.pkg != null) {
20803                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20804                    if (v < vers) vers = v;
20805                }
20806            }
20807            return vers;
20808        } else if (obj instanceof PackageSetting) {
20809            final PackageSetting ps = (PackageSetting) obj;
20810            if (ps.pkg != null) {
20811                return ps.pkg.applicationInfo.targetSdkVersion;
20812            }
20813        }
20814        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20815    }
20816
20817    @Override
20818    public void addPreferredActivity(IntentFilter filter, int match,
20819            ComponentName[] set, ComponentName activity, int userId) {
20820        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20821                "Adding preferred");
20822    }
20823
20824    private void addPreferredActivityInternal(IntentFilter filter, int match,
20825            ComponentName[] set, ComponentName activity, boolean always, int userId,
20826            String opname) {
20827        // writer
20828        int callingUid = Binder.getCallingUid();
20829        enforceCrossUserPermission(callingUid, userId,
20830                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20831        if (filter.countActions() == 0) {
20832            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20833            return;
20834        }
20835        synchronized (mPackages) {
20836            if (mContext.checkCallingOrSelfPermission(
20837                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20838                    != PackageManager.PERMISSION_GRANTED) {
20839                if (getUidTargetSdkVersionLockedLPr(callingUid)
20840                        < Build.VERSION_CODES.FROYO) {
20841                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20842                            + callingUid);
20843                    return;
20844                }
20845                mContext.enforceCallingOrSelfPermission(
20846                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20847            }
20848
20849            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20850            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20851                    + userId + ":");
20852            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20853            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20854            scheduleWritePackageRestrictionsLocked(userId);
20855            postPreferredActivityChangedBroadcast(userId);
20856        }
20857    }
20858
20859    private void postPreferredActivityChangedBroadcast(int userId) {
20860        mHandler.post(() -> {
20861            final IActivityManager am = ActivityManager.getService();
20862            if (am == null) {
20863                return;
20864            }
20865
20866            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20867            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20868            try {
20869                am.broadcastIntent(null, intent, null, null,
20870                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20871                        null, false, false, userId);
20872            } catch (RemoteException e) {
20873            }
20874        });
20875    }
20876
20877    @Override
20878    public void replacePreferredActivity(IntentFilter filter, int match,
20879            ComponentName[] set, ComponentName activity, int userId) {
20880        if (filter.countActions() != 1) {
20881            throw new IllegalArgumentException(
20882                    "replacePreferredActivity expects filter to have only 1 action.");
20883        }
20884        if (filter.countDataAuthorities() != 0
20885                || filter.countDataPaths() != 0
20886                || filter.countDataSchemes() > 1
20887                || filter.countDataTypes() != 0) {
20888            throw new IllegalArgumentException(
20889                    "replacePreferredActivity expects filter to have no data authorities, " +
20890                    "paths, or types; and at most one scheme.");
20891        }
20892
20893        final int callingUid = Binder.getCallingUid();
20894        enforceCrossUserPermission(callingUid, userId,
20895                true /* requireFullPermission */, false /* checkShell */,
20896                "replace preferred activity");
20897        synchronized (mPackages) {
20898            if (mContext.checkCallingOrSelfPermission(
20899                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20900                    != PackageManager.PERMISSION_GRANTED) {
20901                if (getUidTargetSdkVersionLockedLPr(callingUid)
20902                        < Build.VERSION_CODES.FROYO) {
20903                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20904                            + Binder.getCallingUid());
20905                    return;
20906                }
20907                mContext.enforceCallingOrSelfPermission(
20908                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20909            }
20910
20911            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20912            if (pir != null) {
20913                // Get all of the existing entries that exactly match this filter.
20914                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20915                if (existing != null && existing.size() == 1) {
20916                    PreferredActivity cur = existing.get(0);
20917                    if (DEBUG_PREFERRED) {
20918                        Slog.i(TAG, "Checking replace of preferred:");
20919                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20920                        if (!cur.mPref.mAlways) {
20921                            Slog.i(TAG, "  -- CUR; not mAlways!");
20922                        } else {
20923                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20924                            Slog.i(TAG, "  -- CUR: mSet="
20925                                    + Arrays.toString(cur.mPref.mSetComponents));
20926                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20927                            Slog.i(TAG, "  -- NEW: mMatch="
20928                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20929                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20930                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20931                        }
20932                    }
20933                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20934                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20935                            && cur.mPref.sameSet(set)) {
20936                        // Setting the preferred activity to what it happens to be already
20937                        if (DEBUG_PREFERRED) {
20938                            Slog.i(TAG, "Replacing with same preferred activity "
20939                                    + cur.mPref.mShortComponent + " for user "
20940                                    + userId + ":");
20941                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20942                        }
20943                        return;
20944                    }
20945                }
20946
20947                if (existing != null) {
20948                    if (DEBUG_PREFERRED) {
20949                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20950                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20951                    }
20952                    for (int i = 0; i < existing.size(); i++) {
20953                        PreferredActivity pa = existing.get(i);
20954                        if (DEBUG_PREFERRED) {
20955                            Slog.i(TAG, "Removing existing preferred activity "
20956                                    + pa.mPref.mComponent + ":");
20957                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20958                        }
20959                        pir.removeFilter(pa);
20960                    }
20961                }
20962            }
20963            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20964                    "Replacing preferred");
20965        }
20966    }
20967
20968    @Override
20969    public void clearPackagePreferredActivities(String packageName) {
20970        final int callingUid = Binder.getCallingUid();
20971        if (getInstantAppPackageName(callingUid) != null) {
20972            return;
20973        }
20974        // writer
20975        synchronized (mPackages) {
20976            PackageParser.Package pkg = mPackages.get(packageName);
20977            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20978                if (mContext.checkCallingOrSelfPermission(
20979                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20980                        != PackageManager.PERMISSION_GRANTED) {
20981                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20982                            < Build.VERSION_CODES.FROYO) {
20983                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20984                                + callingUid);
20985                        return;
20986                    }
20987                    mContext.enforceCallingOrSelfPermission(
20988                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20989                }
20990            }
20991            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20992            if (ps != null
20993                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20994                return;
20995            }
20996            int user = UserHandle.getCallingUserId();
20997            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20998                scheduleWritePackageRestrictionsLocked(user);
20999            }
21000        }
21001    }
21002
21003    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21004    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
21005        ArrayList<PreferredActivity> removed = null;
21006        boolean changed = false;
21007        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21008            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
21009            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21010            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
21011                continue;
21012            }
21013            Iterator<PreferredActivity> it = pir.filterIterator();
21014            while (it.hasNext()) {
21015                PreferredActivity pa = it.next();
21016                // Mark entry for removal only if it matches the package name
21017                // and the entry is of type "always".
21018                if (packageName == null ||
21019                        (pa.mPref.mComponent.getPackageName().equals(packageName)
21020                                && pa.mPref.mAlways)) {
21021                    if (removed == null) {
21022                        removed = new ArrayList<PreferredActivity>();
21023                    }
21024                    removed.add(pa);
21025                }
21026            }
21027            if (removed != null) {
21028                for (int j=0; j<removed.size(); j++) {
21029                    PreferredActivity pa = removed.get(j);
21030                    pir.removeFilter(pa);
21031                }
21032                changed = true;
21033            }
21034        }
21035        if (changed) {
21036            postPreferredActivityChangedBroadcast(userId);
21037        }
21038        return changed;
21039    }
21040
21041    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21042    private void clearIntentFilterVerificationsLPw(int userId) {
21043        final int packageCount = mPackages.size();
21044        for (int i = 0; i < packageCount; i++) {
21045            PackageParser.Package pkg = mPackages.valueAt(i);
21046            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
21047        }
21048    }
21049
21050    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21051    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
21052        if (userId == UserHandle.USER_ALL) {
21053            if (mSettings.removeIntentFilterVerificationLPw(packageName,
21054                    sUserManager.getUserIds())) {
21055                for (int oneUserId : sUserManager.getUserIds()) {
21056                    scheduleWritePackageRestrictionsLocked(oneUserId);
21057                }
21058            }
21059        } else {
21060            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
21061                scheduleWritePackageRestrictionsLocked(userId);
21062            }
21063        }
21064    }
21065
21066    /** Clears state for all users, and touches intent filter verification policy */
21067    void clearDefaultBrowserIfNeeded(String packageName) {
21068        for (int oneUserId : sUserManager.getUserIds()) {
21069            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
21070        }
21071    }
21072
21073    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
21074        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
21075        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
21076            if (packageName.equals(defaultBrowserPackageName)) {
21077                setDefaultBrowserPackageName(null, userId);
21078            }
21079        }
21080    }
21081
21082    @Override
21083    public void resetApplicationPreferences(int userId) {
21084        mContext.enforceCallingOrSelfPermission(
21085                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
21086        final long identity = Binder.clearCallingIdentity();
21087        // writer
21088        try {
21089            synchronized (mPackages) {
21090                clearPackagePreferredActivitiesLPw(null, userId);
21091                mSettings.applyDefaultPreferredAppsLPw(this, userId);
21092                // TODO: We have to reset the default SMS and Phone. This requires
21093                // significant refactoring to keep all default apps in the package
21094                // manager (cleaner but more work) or have the services provide
21095                // callbacks to the package manager to request a default app reset.
21096                applyFactoryDefaultBrowserLPw(userId);
21097                clearIntentFilterVerificationsLPw(userId);
21098                primeDomainVerificationsLPw(userId);
21099                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
21100                scheduleWritePackageRestrictionsLocked(userId);
21101            }
21102            resetNetworkPolicies(userId);
21103        } finally {
21104            Binder.restoreCallingIdentity(identity);
21105        }
21106    }
21107
21108    @Override
21109    public int getPreferredActivities(List<IntentFilter> outFilters,
21110            List<ComponentName> outActivities, String packageName) {
21111        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21112            return 0;
21113        }
21114        int num = 0;
21115        final int userId = UserHandle.getCallingUserId();
21116        // reader
21117        synchronized (mPackages) {
21118            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
21119            if (pir != null) {
21120                final Iterator<PreferredActivity> it = pir.filterIterator();
21121                while (it.hasNext()) {
21122                    final PreferredActivity pa = it.next();
21123                    if (packageName == null
21124                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
21125                                    && pa.mPref.mAlways)) {
21126                        if (outFilters != null) {
21127                            outFilters.add(new IntentFilter(pa));
21128                        }
21129                        if (outActivities != null) {
21130                            outActivities.add(pa.mPref.mComponent);
21131                        }
21132                    }
21133                }
21134            }
21135        }
21136
21137        return num;
21138    }
21139
21140    @Override
21141    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
21142            int userId) {
21143        int callingUid = Binder.getCallingUid();
21144        if (callingUid != Process.SYSTEM_UID) {
21145            throw new SecurityException(
21146                    "addPersistentPreferredActivity can only be run by the system");
21147        }
21148        if (filter.countActions() == 0) {
21149            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
21150            return;
21151        }
21152        synchronized (mPackages) {
21153            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
21154                    ":");
21155            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
21156            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
21157                    new PersistentPreferredActivity(filter, activity));
21158            scheduleWritePackageRestrictionsLocked(userId);
21159            postPreferredActivityChangedBroadcast(userId);
21160        }
21161    }
21162
21163    @Override
21164    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
21165        int callingUid = Binder.getCallingUid();
21166        if (callingUid != Process.SYSTEM_UID) {
21167            throw new SecurityException(
21168                    "clearPackagePersistentPreferredActivities can only be run by the system");
21169        }
21170        ArrayList<PersistentPreferredActivity> removed = null;
21171        boolean changed = false;
21172        synchronized (mPackages) {
21173            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21174                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21175                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21176                        .valueAt(i);
21177                if (userId != thisUserId) {
21178                    continue;
21179                }
21180                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21181                while (it.hasNext()) {
21182                    PersistentPreferredActivity ppa = it.next();
21183                    // Mark entry for removal only if it matches the package name.
21184                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21185                        if (removed == null) {
21186                            removed = new ArrayList<PersistentPreferredActivity>();
21187                        }
21188                        removed.add(ppa);
21189                    }
21190                }
21191                if (removed != null) {
21192                    for (int j=0; j<removed.size(); j++) {
21193                        PersistentPreferredActivity ppa = removed.get(j);
21194                        ppir.removeFilter(ppa);
21195                    }
21196                    changed = true;
21197                }
21198            }
21199
21200            if (changed) {
21201                scheduleWritePackageRestrictionsLocked(userId);
21202                postPreferredActivityChangedBroadcast(userId);
21203            }
21204        }
21205    }
21206
21207    /**
21208     * Common machinery for picking apart a restored XML blob and passing
21209     * it to a caller-supplied functor to be applied to the running system.
21210     */
21211    private void restoreFromXml(XmlPullParser parser, int userId,
21212            String expectedStartTag, BlobXmlRestorer functor)
21213            throws IOException, XmlPullParserException {
21214        int type;
21215        while ((type = parser.next()) != XmlPullParser.START_TAG
21216                && type != XmlPullParser.END_DOCUMENT) {
21217        }
21218        if (type != XmlPullParser.START_TAG) {
21219            // oops didn't find a start tag?!
21220            if (DEBUG_BACKUP) {
21221                Slog.e(TAG, "Didn't find start tag during restore");
21222            }
21223            return;
21224        }
21225Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21226        // this is supposed to be TAG_PREFERRED_BACKUP
21227        if (!expectedStartTag.equals(parser.getName())) {
21228            if (DEBUG_BACKUP) {
21229                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21230            }
21231            return;
21232        }
21233
21234        // skip interfering stuff, then we're aligned with the backing implementation
21235        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21236Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21237        functor.apply(parser, userId);
21238    }
21239
21240    private interface BlobXmlRestorer {
21241        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21242    }
21243
21244    /**
21245     * Non-Binder method, support for the backup/restore mechanism: write the
21246     * full set of preferred activities in its canonical XML format.  Returns the
21247     * XML output as a byte array, or null if there is none.
21248     */
21249    @Override
21250    public byte[] getPreferredActivityBackup(int userId) {
21251        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21252            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21253        }
21254
21255        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21256        try {
21257            final XmlSerializer serializer = new FastXmlSerializer();
21258            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21259            serializer.startDocument(null, true);
21260            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21261
21262            synchronized (mPackages) {
21263                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21264            }
21265
21266            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21267            serializer.endDocument();
21268            serializer.flush();
21269        } catch (Exception e) {
21270            if (DEBUG_BACKUP) {
21271                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21272            }
21273            return null;
21274        }
21275
21276        return dataStream.toByteArray();
21277    }
21278
21279    @Override
21280    public void restorePreferredActivities(byte[] backup, int userId) {
21281        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21282            throw new SecurityException("Only the system may call restorePreferredActivities()");
21283        }
21284
21285        try {
21286            final XmlPullParser parser = Xml.newPullParser();
21287            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21288            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21289                    new BlobXmlRestorer() {
21290                        @Override
21291                        public void apply(XmlPullParser parser, int userId)
21292                                throws XmlPullParserException, IOException {
21293                            synchronized (mPackages) {
21294                                mSettings.readPreferredActivitiesLPw(parser, userId);
21295                            }
21296                        }
21297                    } );
21298        } catch (Exception e) {
21299            if (DEBUG_BACKUP) {
21300                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21301            }
21302        }
21303    }
21304
21305    /**
21306     * Non-Binder method, support for the backup/restore mechanism: write the
21307     * default browser (etc) settings in its canonical XML format.  Returns the default
21308     * browser XML representation as a byte array, or null if there is none.
21309     */
21310    @Override
21311    public byte[] getDefaultAppsBackup(int userId) {
21312        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21313            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21314        }
21315
21316        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21317        try {
21318            final XmlSerializer serializer = new FastXmlSerializer();
21319            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21320            serializer.startDocument(null, true);
21321            serializer.startTag(null, TAG_DEFAULT_APPS);
21322
21323            synchronized (mPackages) {
21324                mSettings.writeDefaultAppsLPr(serializer, userId);
21325            }
21326
21327            serializer.endTag(null, TAG_DEFAULT_APPS);
21328            serializer.endDocument();
21329            serializer.flush();
21330        } catch (Exception e) {
21331            if (DEBUG_BACKUP) {
21332                Slog.e(TAG, "Unable to write default apps for backup", e);
21333            }
21334            return null;
21335        }
21336
21337        return dataStream.toByteArray();
21338    }
21339
21340    @Override
21341    public void restoreDefaultApps(byte[] backup, int userId) {
21342        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21343            throw new SecurityException("Only the system may call restoreDefaultApps()");
21344        }
21345
21346        try {
21347            final XmlPullParser parser = Xml.newPullParser();
21348            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21349            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21350                    new BlobXmlRestorer() {
21351                        @Override
21352                        public void apply(XmlPullParser parser, int userId)
21353                                throws XmlPullParserException, IOException {
21354                            synchronized (mPackages) {
21355                                mSettings.readDefaultAppsLPw(parser, userId);
21356                            }
21357                        }
21358                    } );
21359        } catch (Exception e) {
21360            if (DEBUG_BACKUP) {
21361                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21362            }
21363        }
21364    }
21365
21366    @Override
21367    public byte[] getIntentFilterVerificationBackup(int userId) {
21368        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21369            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21370        }
21371
21372        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21373        try {
21374            final XmlSerializer serializer = new FastXmlSerializer();
21375            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21376            serializer.startDocument(null, true);
21377            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21378
21379            synchronized (mPackages) {
21380                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21381            }
21382
21383            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21384            serializer.endDocument();
21385            serializer.flush();
21386        } catch (Exception e) {
21387            if (DEBUG_BACKUP) {
21388                Slog.e(TAG, "Unable to write default apps for backup", e);
21389            }
21390            return null;
21391        }
21392
21393        return dataStream.toByteArray();
21394    }
21395
21396    @Override
21397    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21398        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21399            throw new SecurityException("Only the system may call restorePreferredActivities()");
21400        }
21401
21402        try {
21403            final XmlPullParser parser = Xml.newPullParser();
21404            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21405            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21406                    new BlobXmlRestorer() {
21407                        @Override
21408                        public void apply(XmlPullParser parser, int userId)
21409                                throws XmlPullParserException, IOException {
21410                            synchronized (mPackages) {
21411                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21412                                mSettings.writeLPr();
21413                            }
21414                        }
21415                    } );
21416        } catch (Exception e) {
21417            if (DEBUG_BACKUP) {
21418                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21419            }
21420        }
21421    }
21422
21423    @Override
21424    public byte[] getPermissionGrantBackup(int userId) {
21425        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21426            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21427        }
21428
21429        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21430        try {
21431            final XmlSerializer serializer = new FastXmlSerializer();
21432            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21433            serializer.startDocument(null, true);
21434            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21435
21436            synchronized (mPackages) {
21437                serializeRuntimePermissionGrantsLPr(serializer, userId);
21438            }
21439
21440            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21441            serializer.endDocument();
21442            serializer.flush();
21443        } catch (Exception e) {
21444            if (DEBUG_BACKUP) {
21445                Slog.e(TAG, "Unable to write default apps for backup", e);
21446            }
21447            return null;
21448        }
21449
21450        return dataStream.toByteArray();
21451    }
21452
21453    @Override
21454    public void restorePermissionGrants(byte[] backup, int userId) {
21455        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21456            throw new SecurityException("Only the system may call restorePermissionGrants()");
21457        }
21458
21459        try {
21460            final XmlPullParser parser = Xml.newPullParser();
21461            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21462            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21463                    new BlobXmlRestorer() {
21464                        @Override
21465                        public void apply(XmlPullParser parser, int userId)
21466                                throws XmlPullParserException, IOException {
21467                            synchronized (mPackages) {
21468                                processRestoredPermissionGrantsLPr(parser, userId);
21469                            }
21470                        }
21471                    } );
21472        } catch (Exception e) {
21473            if (DEBUG_BACKUP) {
21474                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21475            }
21476        }
21477    }
21478
21479    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21480            throws IOException {
21481        serializer.startTag(null, TAG_ALL_GRANTS);
21482
21483        final int N = mSettings.mPackages.size();
21484        for (int i = 0; i < N; i++) {
21485            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21486            boolean pkgGrantsKnown = false;
21487
21488            PermissionsState packagePerms = ps.getPermissionsState();
21489
21490            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21491                final int grantFlags = state.getFlags();
21492                // only look at grants that are not system/policy fixed
21493                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21494                    final boolean isGranted = state.isGranted();
21495                    // And only back up the user-twiddled state bits
21496                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21497                        final String packageName = mSettings.mPackages.keyAt(i);
21498                        if (!pkgGrantsKnown) {
21499                            serializer.startTag(null, TAG_GRANT);
21500                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21501                            pkgGrantsKnown = true;
21502                        }
21503
21504                        final boolean userSet =
21505                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21506                        final boolean userFixed =
21507                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21508                        final boolean revoke =
21509                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21510
21511                        serializer.startTag(null, TAG_PERMISSION);
21512                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21513                        if (isGranted) {
21514                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21515                        }
21516                        if (userSet) {
21517                            serializer.attribute(null, ATTR_USER_SET, "true");
21518                        }
21519                        if (userFixed) {
21520                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21521                        }
21522                        if (revoke) {
21523                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21524                        }
21525                        serializer.endTag(null, TAG_PERMISSION);
21526                    }
21527                }
21528            }
21529
21530            if (pkgGrantsKnown) {
21531                serializer.endTag(null, TAG_GRANT);
21532            }
21533        }
21534
21535        serializer.endTag(null, TAG_ALL_GRANTS);
21536    }
21537
21538    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21539            throws XmlPullParserException, IOException {
21540        String pkgName = null;
21541        int outerDepth = parser.getDepth();
21542        int type;
21543        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21544                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21545            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21546                continue;
21547            }
21548
21549            final String tagName = parser.getName();
21550            if (tagName.equals(TAG_GRANT)) {
21551                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21552                if (DEBUG_BACKUP) {
21553                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21554                }
21555            } else if (tagName.equals(TAG_PERMISSION)) {
21556
21557                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21558                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21559
21560                int newFlagSet = 0;
21561                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21562                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21563                }
21564                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21565                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21566                }
21567                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21568                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21569                }
21570                if (DEBUG_BACKUP) {
21571                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21572                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21573                }
21574                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21575                if (ps != null) {
21576                    // Already installed so we apply the grant immediately
21577                    if (DEBUG_BACKUP) {
21578                        Slog.v(TAG, "        + already installed; applying");
21579                    }
21580                    PermissionsState perms = ps.getPermissionsState();
21581                    BasePermission bp = mSettings.mPermissions.get(permName);
21582                    if (bp != null) {
21583                        if (isGranted) {
21584                            perms.grantRuntimePermission(bp, userId);
21585                        }
21586                        if (newFlagSet != 0) {
21587                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21588                        }
21589                    }
21590                } else {
21591                    // Need to wait for post-restore install to apply the grant
21592                    if (DEBUG_BACKUP) {
21593                        Slog.v(TAG, "        - not yet installed; saving for later");
21594                    }
21595                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21596                            isGranted, newFlagSet, userId);
21597                }
21598            } else {
21599                PackageManagerService.reportSettingsProblem(Log.WARN,
21600                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21601                XmlUtils.skipCurrentTag(parser);
21602            }
21603        }
21604
21605        scheduleWriteSettingsLocked();
21606        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21607    }
21608
21609    @Override
21610    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21611            int sourceUserId, int targetUserId, int flags) {
21612        mContext.enforceCallingOrSelfPermission(
21613                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21614        int callingUid = Binder.getCallingUid();
21615        enforceOwnerRights(ownerPackage, callingUid);
21616        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21617        if (intentFilter.countActions() == 0) {
21618            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21619            return;
21620        }
21621        synchronized (mPackages) {
21622            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21623                    ownerPackage, targetUserId, flags);
21624            CrossProfileIntentResolver resolver =
21625                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21626            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21627            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21628            if (existing != null) {
21629                int size = existing.size();
21630                for (int i = 0; i < size; i++) {
21631                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21632                        return;
21633                    }
21634                }
21635            }
21636            resolver.addFilter(newFilter);
21637            scheduleWritePackageRestrictionsLocked(sourceUserId);
21638        }
21639    }
21640
21641    @Override
21642    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21643        mContext.enforceCallingOrSelfPermission(
21644                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21645        final int callingUid = Binder.getCallingUid();
21646        enforceOwnerRights(ownerPackage, callingUid);
21647        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21648        synchronized (mPackages) {
21649            CrossProfileIntentResolver resolver =
21650                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21651            ArraySet<CrossProfileIntentFilter> set =
21652                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21653            for (CrossProfileIntentFilter filter : set) {
21654                if (filter.getOwnerPackage().equals(ownerPackage)) {
21655                    resolver.removeFilter(filter);
21656                }
21657            }
21658            scheduleWritePackageRestrictionsLocked(sourceUserId);
21659        }
21660    }
21661
21662    // Enforcing that callingUid is owning pkg on userId
21663    private void enforceOwnerRights(String pkg, int callingUid) {
21664        // The system owns everything.
21665        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21666            return;
21667        }
21668        final int callingUserId = UserHandle.getUserId(callingUid);
21669        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21670        if (pi == null) {
21671            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21672                    + callingUserId);
21673        }
21674        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21675            throw new SecurityException("Calling uid " + callingUid
21676                    + " does not own package " + pkg);
21677        }
21678    }
21679
21680    @Override
21681    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21682        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21683            return null;
21684        }
21685        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21686    }
21687
21688    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21689        UserManagerService ums = UserManagerService.getInstance();
21690        if (ums != null) {
21691            final UserInfo parent = ums.getProfileParent(userId);
21692            final int launcherUid = (parent != null) ? parent.id : userId;
21693            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21694            if (launcherComponent != null) {
21695                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21696                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21697                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21698                        .setPackage(launcherComponent.getPackageName());
21699                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21700            }
21701        }
21702    }
21703
21704    /**
21705     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21706     * then reports the most likely home activity or null if there are more than one.
21707     */
21708    private ComponentName getDefaultHomeActivity(int userId) {
21709        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21710        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21711        if (cn != null) {
21712            return cn;
21713        }
21714
21715        // Find the launcher with the highest priority and return that component if there are no
21716        // other home activity with the same priority.
21717        int lastPriority = Integer.MIN_VALUE;
21718        ComponentName lastComponent = null;
21719        final int size = allHomeCandidates.size();
21720        for (int i = 0; i < size; i++) {
21721            final ResolveInfo ri = allHomeCandidates.get(i);
21722            if (ri.priority > lastPriority) {
21723                lastComponent = ri.activityInfo.getComponentName();
21724                lastPriority = ri.priority;
21725            } else if (ri.priority == lastPriority) {
21726                // Two components found with same priority.
21727                lastComponent = null;
21728            }
21729        }
21730        return lastComponent;
21731    }
21732
21733    private Intent getHomeIntent() {
21734        Intent intent = new Intent(Intent.ACTION_MAIN);
21735        intent.addCategory(Intent.CATEGORY_HOME);
21736        intent.addCategory(Intent.CATEGORY_DEFAULT);
21737        return intent;
21738    }
21739
21740    private IntentFilter getHomeFilter() {
21741        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21742        filter.addCategory(Intent.CATEGORY_HOME);
21743        filter.addCategory(Intent.CATEGORY_DEFAULT);
21744        return filter;
21745    }
21746
21747    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21748            int userId) {
21749        Intent intent  = getHomeIntent();
21750        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21751                PackageManager.GET_META_DATA, userId);
21752        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21753                true, false, false, userId);
21754
21755        allHomeCandidates.clear();
21756        if (list != null) {
21757            for (ResolveInfo ri : list) {
21758                allHomeCandidates.add(ri);
21759            }
21760        }
21761        return (preferred == null || preferred.activityInfo == null)
21762                ? null
21763                : new ComponentName(preferred.activityInfo.packageName,
21764                        preferred.activityInfo.name);
21765    }
21766
21767    @Override
21768    public void setHomeActivity(ComponentName comp, int userId) {
21769        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21770            return;
21771        }
21772        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21773        getHomeActivitiesAsUser(homeActivities, userId);
21774
21775        boolean found = false;
21776
21777        final int size = homeActivities.size();
21778        final ComponentName[] set = new ComponentName[size];
21779        for (int i = 0; i < size; i++) {
21780            final ResolveInfo candidate = homeActivities.get(i);
21781            final ActivityInfo info = candidate.activityInfo;
21782            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21783            set[i] = activityName;
21784            if (!found && activityName.equals(comp)) {
21785                found = true;
21786            }
21787        }
21788        if (!found) {
21789            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21790                    + userId);
21791        }
21792        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21793                set, comp, userId);
21794    }
21795
21796    private @Nullable String getSetupWizardPackageName() {
21797        final Intent intent = new Intent(Intent.ACTION_MAIN);
21798        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21799
21800        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21801                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21802                        | MATCH_DISABLED_COMPONENTS,
21803                UserHandle.myUserId());
21804        if (matches.size() == 1) {
21805            return matches.get(0).getComponentInfo().packageName;
21806        } else {
21807            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21808                    + ": matches=" + matches);
21809            return null;
21810        }
21811    }
21812
21813    private @Nullable String getStorageManagerPackageName() {
21814        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21815
21816        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21817                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21818                        | MATCH_DISABLED_COMPONENTS,
21819                UserHandle.myUserId());
21820        if (matches.size() == 1) {
21821            return matches.get(0).getComponentInfo().packageName;
21822        } else {
21823            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21824                    + matches.size() + ": matches=" + matches);
21825            return null;
21826        }
21827    }
21828
21829    @Override
21830    public void setApplicationEnabledSetting(String appPackageName,
21831            int newState, int flags, int userId, String callingPackage) {
21832        if (!sUserManager.exists(userId)) return;
21833        if (callingPackage == null) {
21834            callingPackage = Integer.toString(Binder.getCallingUid());
21835        }
21836        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21837    }
21838
21839    @Override
21840    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21841        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21842        synchronized (mPackages) {
21843            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21844            if (pkgSetting != null) {
21845                pkgSetting.setUpdateAvailable(updateAvailable);
21846            }
21847        }
21848    }
21849
21850    @Override
21851    public void setComponentEnabledSetting(ComponentName componentName,
21852            int newState, int flags, int userId) {
21853        if (!sUserManager.exists(userId)) return;
21854        setEnabledSetting(componentName.getPackageName(),
21855                componentName.getClassName(), newState, flags, userId, null);
21856    }
21857
21858    private void setEnabledSetting(final String packageName, String className, int newState,
21859            final int flags, int userId, String callingPackage) {
21860        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21861              || newState == COMPONENT_ENABLED_STATE_ENABLED
21862              || newState == COMPONENT_ENABLED_STATE_DISABLED
21863              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21864              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21865            throw new IllegalArgumentException("Invalid new component state: "
21866                    + newState);
21867        }
21868        PackageSetting pkgSetting;
21869        final int callingUid = Binder.getCallingUid();
21870        final int permission;
21871        if (callingUid == Process.SYSTEM_UID) {
21872            permission = PackageManager.PERMISSION_GRANTED;
21873        } else {
21874            permission = mContext.checkCallingOrSelfPermission(
21875                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21876        }
21877        enforceCrossUserPermission(callingUid, userId,
21878                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21879        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21880        boolean sendNow = false;
21881        boolean isApp = (className == null);
21882        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21883        String componentName = isApp ? packageName : className;
21884        int packageUid = -1;
21885        ArrayList<String> components;
21886
21887        // reader
21888        synchronized (mPackages) {
21889            pkgSetting = mSettings.mPackages.get(packageName);
21890            if (pkgSetting == null) {
21891                if (!isCallerInstantApp) {
21892                    if (className == null) {
21893                        throw new IllegalArgumentException("Unknown package: " + packageName);
21894                    }
21895                    throw new IllegalArgumentException(
21896                            "Unknown component: " + packageName + "/" + className);
21897                } else {
21898                    // throw SecurityException to prevent leaking package information
21899                    throw new SecurityException(
21900                            "Attempt to change component state; "
21901                            + "pid=" + Binder.getCallingPid()
21902                            + ", uid=" + callingUid
21903                            + (className == null
21904                                    ? ", package=" + packageName
21905                                    : ", component=" + packageName + "/" + className));
21906                }
21907            }
21908        }
21909
21910        // Limit who can change which apps
21911        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21912            // Don't allow apps that don't have permission to modify other apps
21913            if (!allowedByPermission
21914                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21915                throw new SecurityException(
21916                        "Attempt to change component state; "
21917                        + "pid=" + Binder.getCallingPid()
21918                        + ", uid=" + callingUid
21919                        + (className == null
21920                                ? ", package=" + packageName
21921                                : ", component=" + packageName + "/" + className));
21922            }
21923            // Don't allow changing protected packages.
21924            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21925                throw new SecurityException("Cannot disable a protected package: " + packageName);
21926            }
21927        }
21928
21929        synchronized (mPackages) {
21930            if (callingUid == Process.SHELL_UID
21931                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21932                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21933                // unless it is a test package.
21934                int oldState = pkgSetting.getEnabled(userId);
21935                if (className == null
21936                        &&
21937                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21938                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21939                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21940                        &&
21941                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21942                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21943                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21944                    // ok
21945                } else {
21946                    throw new SecurityException(
21947                            "Shell cannot change component state for " + packageName + "/"
21948                                    + className + " to " + newState);
21949                }
21950            }
21951        }
21952        if (className == null) {
21953            // We're dealing with an application/package level state change
21954            synchronized (mPackages) {
21955                if (pkgSetting.getEnabled(userId) == newState) {
21956                    // Nothing to do
21957                    return;
21958                }
21959            }
21960            // If we're enabling a system stub, there's a little more work to do.
21961            // Prior to enabling the package, we need to decompress the APK(s) to the
21962            // data partition and then replace the version on the system partition.
21963            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21964            final boolean isSystemStub = deletedPkg.isStub
21965                    && deletedPkg.isSystemApp();
21966            if (isSystemStub
21967                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21968                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21969                final File codePath = decompressPackage(deletedPkg);
21970                if (codePath == null) {
21971                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21972                    return;
21973                }
21974                // TODO remove direct parsing of the package object during internal cleanup
21975                // of scan package
21976                // We need to call parse directly here for no other reason than we need
21977                // the new package in order to disable the old one [we use the information
21978                // for some internal optimization to optionally create a new package setting
21979                // object on replace]. However, we can't get the package from the scan
21980                // because the scan modifies live structures and we need to remove the
21981                // old [system] package from the system before a scan can be attempted.
21982                // Once scan is indempotent we can remove this parse and use the package
21983                // object we scanned, prior to adding it to package settings.
21984                final PackageParser pp = new PackageParser();
21985                pp.setSeparateProcesses(mSeparateProcesses);
21986                pp.setDisplayMetrics(mMetrics);
21987                pp.setCallback(mPackageParserCallback);
21988                final PackageParser.Package tmpPkg;
21989                try {
21990                    final int parseFlags = mDefParseFlags
21991                            | PackageParser.PARSE_MUST_BE_APK
21992                            | PackageParser.PARSE_IS_SYSTEM
21993                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21994                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21995                } catch (PackageParserException e) {
21996                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21997                    return;
21998                }
21999                synchronized (mInstallLock) {
22000                    // Disable the stub and remove any package entries
22001                    removePackageLI(deletedPkg, true);
22002                    synchronized (mPackages) {
22003                        disableSystemPackageLPw(deletedPkg, tmpPkg);
22004                    }
22005                    final PackageParser.Package newPkg;
22006                    try (PackageFreezer freezer =
22007                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
22008                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
22009                                | PackageParser.PARSE_ENFORCE_CODE;
22010                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
22011                                0 /*currentTime*/, null /*user*/);
22012                        prepareAppDataAfterInstallLIF(newPkg);
22013                        synchronized (mPackages) {
22014                            try {
22015                                updateSharedLibrariesLPr(newPkg, null);
22016                            } catch (PackageManagerException e) {
22017                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
22018                            }
22019                            updatePermissionsLPw(newPkg.packageName, newPkg,
22020                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
22021                            mSettings.writeLPr();
22022                        }
22023                    } catch (PackageManagerException e) {
22024                        // Whoops! Something went wrong; try to roll back to the stub
22025                        Slog.w(TAG, "Failed to install compressed system package:"
22026                                + pkgSetting.name, e);
22027                        // Remove the failed install
22028                        removeCodePathLI(codePath);
22029
22030                        // Install the system package
22031                        try (PackageFreezer freezer =
22032                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
22033                            synchronized (mPackages) {
22034                                // NOTE: The system package always needs to be enabled; even
22035                                // if it's for a compressed stub. If we don't, installing the
22036                                // system package fails during scan [scanning checks the disabled
22037                                // packages]. We will reverse this later, after we've "installed"
22038                                // the stub.
22039                                // This leaves us in a fragile state; the stub should never be
22040                                // enabled, so, cross your fingers and hope nothing goes wrong
22041                                // until we can disable the package later.
22042                                enableSystemPackageLPw(deletedPkg);
22043                            }
22044                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
22045                                    false /*isPrivileged*/, null /*allUserHandles*/,
22046                                    null /*origUserHandles*/, null /*origPermissionsState*/,
22047                                    true /*writeSettings*/);
22048                        } catch (PackageManagerException pme) {
22049                            Slog.w(TAG, "Failed to restore system package:"
22050                                    + deletedPkg.packageName, pme);
22051                        } finally {
22052                            synchronized (mPackages) {
22053                                mSettings.disableSystemPackageLPw(
22054                                        deletedPkg.packageName, true /*replaced*/);
22055                                mSettings.writeLPr();
22056                            }
22057                        }
22058                        return;
22059                    }
22060                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
22061                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22062                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
22063                    mDexManager.notifyPackageUpdated(newPkg.packageName,
22064                            newPkg.baseCodePath, newPkg.splitCodePaths);
22065                }
22066            }
22067            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
22068                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
22069                // Don't care about who enables an app.
22070                callingPackage = null;
22071            }
22072            synchronized (mPackages) {
22073                pkgSetting.setEnabled(newState, userId, callingPackage);
22074            }
22075        } else {
22076            synchronized (mPackages) {
22077                // We're dealing with a component level state change
22078                // First, verify that this is a valid class name.
22079                PackageParser.Package pkg = pkgSetting.pkg;
22080                if (pkg == null || !pkg.hasComponentClassName(className)) {
22081                    if (pkg != null &&
22082                            pkg.applicationInfo.targetSdkVersion >=
22083                                    Build.VERSION_CODES.JELLY_BEAN) {
22084                        throw new IllegalArgumentException("Component class " + className
22085                                + " does not exist in " + packageName);
22086                    } else {
22087                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
22088                                + className + " does not exist in " + packageName);
22089                    }
22090                }
22091                switch (newState) {
22092                    case COMPONENT_ENABLED_STATE_ENABLED:
22093                        if (!pkgSetting.enableComponentLPw(className, userId)) {
22094                            return;
22095                        }
22096                        break;
22097                    case COMPONENT_ENABLED_STATE_DISABLED:
22098                        if (!pkgSetting.disableComponentLPw(className, userId)) {
22099                            return;
22100                        }
22101                        break;
22102                    case COMPONENT_ENABLED_STATE_DEFAULT:
22103                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
22104                            return;
22105                        }
22106                        break;
22107                    default:
22108                        Slog.e(TAG, "Invalid new component state: " + newState);
22109                        return;
22110                }
22111            }
22112        }
22113        synchronized (mPackages) {
22114            scheduleWritePackageRestrictionsLocked(userId);
22115            updateSequenceNumberLP(pkgSetting, new int[] { userId });
22116            final long callingId = Binder.clearCallingIdentity();
22117            try {
22118                updateInstantAppInstallerLocked(packageName);
22119            } finally {
22120                Binder.restoreCallingIdentity(callingId);
22121            }
22122            components = mPendingBroadcasts.get(userId, packageName);
22123            final boolean newPackage = components == null;
22124            if (newPackage) {
22125                components = new ArrayList<String>();
22126            }
22127            if (!components.contains(componentName)) {
22128                components.add(componentName);
22129            }
22130            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
22131                sendNow = true;
22132                // Purge entry from pending broadcast list if another one exists already
22133                // since we are sending one right away.
22134                mPendingBroadcasts.remove(userId, packageName);
22135            } else {
22136                if (newPackage) {
22137                    mPendingBroadcasts.put(userId, packageName, components);
22138                }
22139                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
22140                    // Schedule a message
22141                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
22142                }
22143            }
22144        }
22145
22146        long callingId = Binder.clearCallingIdentity();
22147        try {
22148            if (sendNow) {
22149                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
22150                sendPackageChangedBroadcast(packageName,
22151                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
22152            }
22153        } finally {
22154            Binder.restoreCallingIdentity(callingId);
22155        }
22156    }
22157
22158    @Override
22159    public void flushPackageRestrictionsAsUser(int userId) {
22160        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22161            return;
22162        }
22163        if (!sUserManager.exists(userId)) {
22164            return;
22165        }
22166        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
22167                false /* checkShell */, "flushPackageRestrictions");
22168        synchronized (mPackages) {
22169            mSettings.writePackageRestrictionsLPr(userId);
22170            mDirtyUsers.remove(userId);
22171            if (mDirtyUsers.isEmpty()) {
22172                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
22173            }
22174        }
22175    }
22176
22177    private void sendPackageChangedBroadcast(String packageName,
22178            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
22179        if (DEBUG_INSTALL)
22180            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
22181                    + componentNames);
22182        Bundle extras = new Bundle(4);
22183        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
22184        String nameList[] = new String[componentNames.size()];
22185        componentNames.toArray(nameList);
22186        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
22187        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
22188        extras.putInt(Intent.EXTRA_UID, packageUid);
22189        // If this is not reporting a change of the overall package, then only send it
22190        // to registered receivers.  We don't want to launch a swath of apps for every
22191        // little component state change.
22192        final int flags = !componentNames.contains(packageName)
22193                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
22194        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
22195                new int[] {UserHandle.getUserId(packageUid)});
22196    }
22197
22198    @Override
22199    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
22200        if (!sUserManager.exists(userId)) return;
22201        final int callingUid = Binder.getCallingUid();
22202        if (getInstantAppPackageName(callingUid) != null) {
22203            return;
22204        }
22205        final int permission = mContext.checkCallingOrSelfPermission(
22206                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
22207        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
22208        enforceCrossUserPermission(callingUid, userId,
22209                true /* requireFullPermission */, true /* checkShell */, "stop package");
22210        // writer
22211        synchronized (mPackages) {
22212            final PackageSetting ps = mSettings.mPackages.get(packageName);
22213            if (!filterAppAccessLPr(ps, callingUid, userId)
22214                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
22215                            allowedByPermission, callingUid, userId)) {
22216                scheduleWritePackageRestrictionsLocked(userId);
22217            }
22218        }
22219    }
22220
22221    @Override
22222    public String getInstallerPackageName(String packageName) {
22223        final int callingUid = Binder.getCallingUid();
22224        if (getInstantAppPackageName(callingUid) != null) {
22225            return null;
22226        }
22227        // reader
22228        synchronized (mPackages) {
22229            final PackageSetting ps = mSettings.mPackages.get(packageName);
22230            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
22231                return null;
22232            }
22233            return mSettings.getInstallerPackageNameLPr(packageName);
22234        }
22235    }
22236
22237    public boolean isOrphaned(String packageName) {
22238        // reader
22239        synchronized (mPackages) {
22240            return mSettings.isOrphaned(packageName);
22241        }
22242    }
22243
22244    @Override
22245    public int getApplicationEnabledSetting(String packageName, int userId) {
22246        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22247        int callingUid = Binder.getCallingUid();
22248        enforceCrossUserPermission(callingUid, userId,
22249                false /* requireFullPermission */, false /* checkShell */, "get enabled");
22250        // reader
22251        synchronized (mPackages) {
22252            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22253                return COMPONENT_ENABLED_STATE_DISABLED;
22254            }
22255            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22256        }
22257    }
22258
22259    @Override
22260    public int getComponentEnabledSetting(ComponentName component, int userId) {
22261        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22262        int callingUid = Binder.getCallingUid();
22263        enforceCrossUserPermission(callingUid, userId,
22264                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22265        synchronized (mPackages) {
22266            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22267                    component, TYPE_UNKNOWN, userId)) {
22268                return COMPONENT_ENABLED_STATE_DISABLED;
22269            }
22270            return mSettings.getComponentEnabledSettingLPr(component, userId);
22271        }
22272    }
22273
22274    @Override
22275    public void enterSafeMode() {
22276        enforceSystemOrRoot("Only the system can request entering safe mode");
22277
22278        if (!mSystemReady) {
22279            mSafeMode = true;
22280        }
22281    }
22282
22283    @Override
22284    public void systemReady() {
22285        enforceSystemOrRoot("Only the system can claim the system is ready");
22286
22287        mSystemReady = true;
22288        final ContentResolver resolver = mContext.getContentResolver();
22289        ContentObserver co = new ContentObserver(mHandler) {
22290            @Override
22291            public void onChange(boolean selfChange) {
22292                mEphemeralAppsDisabled =
22293                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22294                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22295            }
22296        };
22297        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22298                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22299                false, co, UserHandle.USER_SYSTEM);
22300        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22301                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22302        co.onChange(true);
22303
22304        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22305        // disabled after already being started.
22306        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22307                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22308
22309        // Read the compatibilty setting when the system is ready.
22310        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22311                mContext.getContentResolver(),
22312                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22313        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22314        if (DEBUG_SETTINGS) {
22315            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22316        }
22317
22318        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22319
22320        synchronized (mPackages) {
22321            // Verify that all of the preferred activity components actually
22322            // exist.  It is possible for applications to be updated and at
22323            // that point remove a previously declared activity component that
22324            // had been set as a preferred activity.  We try to clean this up
22325            // the next time we encounter that preferred activity, but it is
22326            // possible for the user flow to never be able to return to that
22327            // situation so here we do a sanity check to make sure we haven't
22328            // left any junk around.
22329            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22330            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22331                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22332                removed.clear();
22333                for (PreferredActivity pa : pir.filterSet()) {
22334                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22335                        removed.add(pa);
22336                    }
22337                }
22338                if (removed.size() > 0) {
22339                    for (int r=0; r<removed.size(); r++) {
22340                        PreferredActivity pa = removed.get(r);
22341                        Slog.w(TAG, "Removing dangling preferred activity: "
22342                                + pa.mPref.mComponent);
22343                        pir.removeFilter(pa);
22344                    }
22345                    mSettings.writePackageRestrictionsLPr(
22346                            mSettings.mPreferredActivities.keyAt(i));
22347                }
22348            }
22349
22350            for (int userId : UserManagerService.getInstance().getUserIds()) {
22351                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22352                    grantPermissionsUserIds = ArrayUtils.appendInt(
22353                            grantPermissionsUserIds, userId);
22354                }
22355            }
22356        }
22357        sUserManager.systemReady();
22358
22359        // If we upgraded grant all default permissions before kicking off.
22360        for (int userId : grantPermissionsUserIds) {
22361            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22362        }
22363
22364        // If we did not grant default permissions, we preload from this the
22365        // default permission exceptions lazily to ensure we don't hit the
22366        // disk on a new user creation.
22367        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22368            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22369        }
22370
22371        // Kick off any messages waiting for system ready
22372        if (mPostSystemReadyMessages != null) {
22373            for (Message msg : mPostSystemReadyMessages) {
22374                msg.sendToTarget();
22375            }
22376            mPostSystemReadyMessages = null;
22377        }
22378
22379        // Watch for external volumes that come and go over time
22380        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22381        storage.registerListener(mStorageListener);
22382
22383        mInstallerService.systemReady();
22384        mPackageDexOptimizer.systemReady();
22385
22386        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22387                StorageManagerInternal.class);
22388        StorageManagerInternal.addExternalStoragePolicy(
22389                new StorageManagerInternal.ExternalStorageMountPolicy() {
22390            @Override
22391            public int getMountMode(int uid, String packageName) {
22392                if (Process.isIsolated(uid)) {
22393                    return Zygote.MOUNT_EXTERNAL_NONE;
22394                }
22395                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22396                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22397                }
22398                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22399                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22400                }
22401                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22402                    return Zygote.MOUNT_EXTERNAL_READ;
22403                }
22404                return Zygote.MOUNT_EXTERNAL_WRITE;
22405            }
22406
22407            @Override
22408            public boolean hasExternalStorage(int uid, String packageName) {
22409                return true;
22410            }
22411        });
22412
22413        // Now that we're mostly running, clean up stale users and apps
22414        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22415        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22416
22417        if (mPrivappPermissionsViolations != null) {
22418            Slog.wtf(TAG,"Signature|privileged permissions not in "
22419                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22420            mPrivappPermissionsViolations = null;
22421        }
22422    }
22423
22424    public void waitForAppDataPrepared() {
22425        if (mPrepareAppDataFuture == null) {
22426            return;
22427        }
22428        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22429        mPrepareAppDataFuture = null;
22430    }
22431
22432    @Override
22433    public boolean isSafeMode() {
22434        // allow instant applications
22435        return mSafeMode;
22436    }
22437
22438    @Override
22439    public boolean hasSystemUidErrors() {
22440        // allow instant applications
22441        return mHasSystemUidErrors;
22442    }
22443
22444    static String arrayToString(int[] array) {
22445        StringBuffer buf = new StringBuffer(128);
22446        buf.append('[');
22447        if (array != null) {
22448            for (int i=0; i<array.length; i++) {
22449                if (i > 0) buf.append(", ");
22450                buf.append(array[i]);
22451            }
22452        }
22453        buf.append(']');
22454        return buf.toString();
22455    }
22456
22457    static class DumpState {
22458        public static final int DUMP_LIBS = 1 << 0;
22459        public static final int DUMP_FEATURES = 1 << 1;
22460        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22461        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22462        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22463        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22464        public static final int DUMP_PERMISSIONS = 1 << 6;
22465        public static final int DUMP_PACKAGES = 1 << 7;
22466        public static final int DUMP_SHARED_USERS = 1 << 8;
22467        public static final int DUMP_MESSAGES = 1 << 9;
22468        public static final int DUMP_PROVIDERS = 1 << 10;
22469        public static final int DUMP_VERIFIERS = 1 << 11;
22470        public static final int DUMP_PREFERRED = 1 << 12;
22471        public static final int DUMP_PREFERRED_XML = 1 << 13;
22472        public static final int DUMP_KEYSETS = 1 << 14;
22473        public static final int DUMP_VERSION = 1 << 15;
22474        public static final int DUMP_INSTALLS = 1 << 16;
22475        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22476        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22477        public static final int DUMP_FROZEN = 1 << 19;
22478        public static final int DUMP_DEXOPT = 1 << 20;
22479        public static final int DUMP_COMPILER_STATS = 1 << 21;
22480        public static final int DUMP_CHANGES = 1 << 22;
22481        public static final int DUMP_VOLUMES = 1 << 23;
22482
22483        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22484
22485        private int mTypes;
22486
22487        private int mOptions;
22488
22489        private boolean mTitlePrinted;
22490
22491        private SharedUserSetting mSharedUser;
22492
22493        public boolean isDumping(int type) {
22494            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22495                return true;
22496            }
22497
22498            return (mTypes & type) != 0;
22499        }
22500
22501        public void setDump(int type) {
22502            mTypes |= type;
22503        }
22504
22505        public boolean isOptionEnabled(int option) {
22506            return (mOptions & option) != 0;
22507        }
22508
22509        public void setOptionEnabled(int option) {
22510            mOptions |= option;
22511        }
22512
22513        public boolean onTitlePrinted() {
22514            final boolean printed = mTitlePrinted;
22515            mTitlePrinted = true;
22516            return printed;
22517        }
22518
22519        public boolean getTitlePrinted() {
22520            return mTitlePrinted;
22521        }
22522
22523        public void setTitlePrinted(boolean enabled) {
22524            mTitlePrinted = enabled;
22525        }
22526
22527        public SharedUserSetting getSharedUser() {
22528            return mSharedUser;
22529        }
22530
22531        public void setSharedUser(SharedUserSetting user) {
22532            mSharedUser = user;
22533        }
22534    }
22535
22536    @Override
22537    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22538            FileDescriptor err, String[] args, ShellCallback callback,
22539            ResultReceiver resultReceiver) {
22540        (new PackageManagerShellCommand(this)).exec(
22541                this, in, out, err, args, callback, resultReceiver);
22542    }
22543
22544    @Override
22545    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22546        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22547
22548        DumpState dumpState = new DumpState();
22549        boolean fullPreferred = false;
22550        boolean checkin = false;
22551
22552        String packageName = null;
22553        ArraySet<String> permissionNames = null;
22554
22555        int opti = 0;
22556        while (opti < args.length) {
22557            String opt = args[opti];
22558            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22559                break;
22560            }
22561            opti++;
22562
22563            if ("-a".equals(opt)) {
22564                // Right now we only know how to print all.
22565            } else if ("-h".equals(opt)) {
22566                pw.println("Package manager dump options:");
22567                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22568                pw.println("    --checkin: dump for a checkin");
22569                pw.println("    -f: print details of intent filters");
22570                pw.println("    -h: print this help");
22571                pw.println("  cmd may be one of:");
22572                pw.println("    l[ibraries]: list known shared libraries");
22573                pw.println("    f[eatures]: list device features");
22574                pw.println("    k[eysets]: print known keysets");
22575                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22576                pw.println("    perm[issions]: dump permissions");
22577                pw.println("    permission [name ...]: dump declaration and use of given permission");
22578                pw.println("    pref[erred]: print preferred package settings");
22579                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22580                pw.println("    prov[iders]: dump content providers");
22581                pw.println("    p[ackages]: dump installed packages");
22582                pw.println("    s[hared-users]: dump shared user IDs");
22583                pw.println("    m[essages]: print collected runtime messages");
22584                pw.println("    v[erifiers]: print package verifier info");
22585                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22586                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22587                pw.println("    version: print database version info");
22588                pw.println("    write: write current settings now");
22589                pw.println("    installs: details about install sessions");
22590                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22591                pw.println("    dexopt: dump dexopt state");
22592                pw.println("    compiler-stats: dump compiler statistics");
22593                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22594                pw.println("    <package.name>: info about given package");
22595                return;
22596            } else if ("--checkin".equals(opt)) {
22597                checkin = true;
22598            } else if ("-f".equals(opt)) {
22599                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22600            } else if ("--proto".equals(opt)) {
22601                dumpProto(fd);
22602                return;
22603            } else {
22604                pw.println("Unknown argument: " + opt + "; use -h for help");
22605            }
22606        }
22607
22608        // Is the caller requesting to dump a particular piece of data?
22609        if (opti < args.length) {
22610            String cmd = args[opti];
22611            opti++;
22612            // Is this a package name?
22613            if ("android".equals(cmd) || cmd.contains(".")) {
22614                packageName = cmd;
22615                // When dumping a single package, we always dump all of its
22616                // filter information since the amount of data will be reasonable.
22617                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22618            } else if ("check-permission".equals(cmd)) {
22619                if (opti >= args.length) {
22620                    pw.println("Error: check-permission missing permission argument");
22621                    return;
22622                }
22623                String perm = args[opti];
22624                opti++;
22625                if (opti >= args.length) {
22626                    pw.println("Error: check-permission missing package argument");
22627                    return;
22628                }
22629
22630                String pkg = args[opti];
22631                opti++;
22632                int user = UserHandle.getUserId(Binder.getCallingUid());
22633                if (opti < args.length) {
22634                    try {
22635                        user = Integer.parseInt(args[opti]);
22636                    } catch (NumberFormatException e) {
22637                        pw.println("Error: check-permission user argument is not a number: "
22638                                + args[opti]);
22639                        return;
22640                    }
22641                }
22642
22643                // Normalize package name to handle renamed packages and static libs
22644                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22645
22646                pw.println(checkPermission(perm, pkg, user));
22647                return;
22648            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22649                dumpState.setDump(DumpState.DUMP_LIBS);
22650            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22651                dumpState.setDump(DumpState.DUMP_FEATURES);
22652            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22653                if (opti >= args.length) {
22654                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22655                            | DumpState.DUMP_SERVICE_RESOLVERS
22656                            | DumpState.DUMP_RECEIVER_RESOLVERS
22657                            | DumpState.DUMP_CONTENT_RESOLVERS);
22658                } else {
22659                    while (opti < args.length) {
22660                        String name = args[opti];
22661                        if ("a".equals(name) || "activity".equals(name)) {
22662                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22663                        } else if ("s".equals(name) || "service".equals(name)) {
22664                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22665                        } else if ("r".equals(name) || "receiver".equals(name)) {
22666                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22667                        } else if ("c".equals(name) || "content".equals(name)) {
22668                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22669                        } else {
22670                            pw.println("Error: unknown resolver table type: " + name);
22671                            return;
22672                        }
22673                        opti++;
22674                    }
22675                }
22676            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22677                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22678            } else if ("permission".equals(cmd)) {
22679                if (opti >= args.length) {
22680                    pw.println("Error: permission requires permission name");
22681                    return;
22682                }
22683                permissionNames = new ArraySet<>();
22684                while (opti < args.length) {
22685                    permissionNames.add(args[opti]);
22686                    opti++;
22687                }
22688                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22689                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22690            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22691                dumpState.setDump(DumpState.DUMP_PREFERRED);
22692            } else if ("preferred-xml".equals(cmd)) {
22693                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22694                if (opti < args.length && "--full".equals(args[opti])) {
22695                    fullPreferred = true;
22696                    opti++;
22697                }
22698            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22699                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22700            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22701                dumpState.setDump(DumpState.DUMP_PACKAGES);
22702            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22703                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22704            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22705                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22706            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22707                dumpState.setDump(DumpState.DUMP_MESSAGES);
22708            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22709                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22710            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22711                    || "intent-filter-verifiers".equals(cmd)) {
22712                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22713            } else if ("version".equals(cmd)) {
22714                dumpState.setDump(DumpState.DUMP_VERSION);
22715            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22716                dumpState.setDump(DumpState.DUMP_KEYSETS);
22717            } else if ("installs".equals(cmd)) {
22718                dumpState.setDump(DumpState.DUMP_INSTALLS);
22719            } else if ("frozen".equals(cmd)) {
22720                dumpState.setDump(DumpState.DUMP_FROZEN);
22721            } else if ("volumes".equals(cmd)) {
22722                dumpState.setDump(DumpState.DUMP_VOLUMES);
22723            } else if ("dexopt".equals(cmd)) {
22724                dumpState.setDump(DumpState.DUMP_DEXOPT);
22725            } else if ("compiler-stats".equals(cmd)) {
22726                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22727            } else if ("changes".equals(cmd)) {
22728                dumpState.setDump(DumpState.DUMP_CHANGES);
22729            } else if ("write".equals(cmd)) {
22730                synchronized (mPackages) {
22731                    mSettings.writeLPr();
22732                    pw.println("Settings written.");
22733                    return;
22734                }
22735            }
22736        }
22737
22738        if (checkin) {
22739            pw.println("vers,1");
22740        }
22741
22742        // reader
22743        synchronized (mPackages) {
22744            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22745                if (!checkin) {
22746                    if (dumpState.onTitlePrinted())
22747                        pw.println();
22748                    pw.println("Database versions:");
22749                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22750                }
22751            }
22752
22753            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22754                if (!checkin) {
22755                    if (dumpState.onTitlePrinted())
22756                        pw.println();
22757                    pw.println("Verifiers:");
22758                    pw.print("  Required: ");
22759                    pw.print(mRequiredVerifierPackage);
22760                    pw.print(" (uid=");
22761                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22762                            UserHandle.USER_SYSTEM));
22763                    pw.println(")");
22764                } else if (mRequiredVerifierPackage != null) {
22765                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22766                    pw.print(",");
22767                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22768                            UserHandle.USER_SYSTEM));
22769                }
22770            }
22771
22772            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22773                    packageName == null) {
22774                if (mIntentFilterVerifierComponent != null) {
22775                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22776                    if (!checkin) {
22777                        if (dumpState.onTitlePrinted())
22778                            pw.println();
22779                        pw.println("Intent Filter Verifier:");
22780                        pw.print("  Using: ");
22781                        pw.print(verifierPackageName);
22782                        pw.print(" (uid=");
22783                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22784                                UserHandle.USER_SYSTEM));
22785                        pw.println(")");
22786                    } else if (verifierPackageName != null) {
22787                        pw.print("ifv,"); pw.print(verifierPackageName);
22788                        pw.print(",");
22789                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22790                                UserHandle.USER_SYSTEM));
22791                    }
22792                } else {
22793                    pw.println();
22794                    pw.println("No Intent Filter Verifier available!");
22795                }
22796            }
22797
22798            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22799                boolean printedHeader = false;
22800                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22801                while (it.hasNext()) {
22802                    String libName = it.next();
22803                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22804                    if (versionedLib == null) {
22805                        continue;
22806                    }
22807                    final int versionCount = versionedLib.size();
22808                    for (int i = 0; i < versionCount; i++) {
22809                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22810                        if (!checkin) {
22811                            if (!printedHeader) {
22812                                if (dumpState.onTitlePrinted())
22813                                    pw.println();
22814                                pw.println("Libraries:");
22815                                printedHeader = true;
22816                            }
22817                            pw.print("  ");
22818                        } else {
22819                            pw.print("lib,");
22820                        }
22821                        pw.print(libEntry.info.getName());
22822                        if (libEntry.info.isStatic()) {
22823                            pw.print(" version=" + libEntry.info.getVersion());
22824                        }
22825                        if (!checkin) {
22826                            pw.print(" -> ");
22827                        }
22828                        if (libEntry.path != null) {
22829                            pw.print(" (jar) ");
22830                            pw.print(libEntry.path);
22831                        } else {
22832                            pw.print(" (apk) ");
22833                            pw.print(libEntry.apk);
22834                        }
22835                        pw.println();
22836                    }
22837                }
22838            }
22839
22840            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22841                if (dumpState.onTitlePrinted())
22842                    pw.println();
22843                if (!checkin) {
22844                    pw.println("Features:");
22845                }
22846
22847                synchronized (mAvailableFeatures) {
22848                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22849                        if (checkin) {
22850                            pw.print("feat,");
22851                            pw.print(feat.name);
22852                            pw.print(",");
22853                            pw.println(feat.version);
22854                        } else {
22855                            pw.print("  ");
22856                            pw.print(feat.name);
22857                            if (feat.version > 0) {
22858                                pw.print(" version=");
22859                                pw.print(feat.version);
22860                            }
22861                            pw.println();
22862                        }
22863                    }
22864                }
22865            }
22866
22867            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22868                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22869                        : "Activity Resolver Table:", "  ", packageName,
22870                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22871                    dumpState.setTitlePrinted(true);
22872                }
22873            }
22874            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22875                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22876                        : "Receiver Resolver Table:", "  ", packageName,
22877                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22878                    dumpState.setTitlePrinted(true);
22879                }
22880            }
22881            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22882                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22883                        : "Service Resolver Table:", "  ", packageName,
22884                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22885                    dumpState.setTitlePrinted(true);
22886                }
22887            }
22888            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22889                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22890                        : "Provider Resolver Table:", "  ", packageName,
22891                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22892                    dumpState.setTitlePrinted(true);
22893                }
22894            }
22895
22896            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22897                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22898                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22899                    int user = mSettings.mPreferredActivities.keyAt(i);
22900                    if (pir.dump(pw,
22901                            dumpState.getTitlePrinted()
22902                                ? "\nPreferred Activities User " + user + ":"
22903                                : "Preferred Activities User " + user + ":", "  ",
22904                            packageName, true, false)) {
22905                        dumpState.setTitlePrinted(true);
22906                    }
22907                }
22908            }
22909
22910            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22911                pw.flush();
22912                FileOutputStream fout = new FileOutputStream(fd);
22913                BufferedOutputStream str = new BufferedOutputStream(fout);
22914                XmlSerializer serializer = new FastXmlSerializer();
22915                try {
22916                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22917                    serializer.startDocument(null, true);
22918                    serializer.setFeature(
22919                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22920                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22921                    serializer.endDocument();
22922                    serializer.flush();
22923                } catch (IllegalArgumentException e) {
22924                    pw.println("Failed writing: " + e);
22925                } catch (IllegalStateException e) {
22926                    pw.println("Failed writing: " + e);
22927                } catch (IOException e) {
22928                    pw.println("Failed writing: " + e);
22929                }
22930            }
22931
22932            if (!checkin
22933                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22934                    && packageName == null) {
22935                pw.println();
22936                int count = mSettings.mPackages.size();
22937                if (count == 0) {
22938                    pw.println("No applications!");
22939                    pw.println();
22940                } else {
22941                    final String prefix = "  ";
22942                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22943                    if (allPackageSettings.size() == 0) {
22944                        pw.println("No domain preferred apps!");
22945                        pw.println();
22946                    } else {
22947                        pw.println("App verification status:");
22948                        pw.println();
22949                        count = 0;
22950                        for (PackageSetting ps : allPackageSettings) {
22951                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22952                            if (ivi == null || ivi.getPackageName() == null) continue;
22953                            pw.println(prefix + "Package: " + ivi.getPackageName());
22954                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22955                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22956                            pw.println();
22957                            count++;
22958                        }
22959                        if (count == 0) {
22960                            pw.println(prefix + "No app verification established.");
22961                            pw.println();
22962                        }
22963                        for (int userId : sUserManager.getUserIds()) {
22964                            pw.println("App linkages for user " + userId + ":");
22965                            pw.println();
22966                            count = 0;
22967                            for (PackageSetting ps : allPackageSettings) {
22968                                final long status = ps.getDomainVerificationStatusForUser(userId);
22969                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22970                                        && !DEBUG_DOMAIN_VERIFICATION) {
22971                                    continue;
22972                                }
22973                                pw.println(prefix + "Package: " + ps.name);
22974                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22975                                String statusStr = IntentFilterVerificationInfo.
22976                                        getStatusStringFromValue(status);
22977                                pw.println(prefix + "Status:  " + statusStr);
22978                                pw.println();
22979                                count++;
22980                            }
22981                            if (count == 0) {
22982                                pw.println(prefix + "No configured app linkages.");
22983                                pw.println();
22984                            }
22985                        }
22986                    }
22987                }
22988            }
22989
22990            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22991                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22992                if (packageName == null && permissionNames == null) {
22993                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22994                        if (iperm == 0) {
22995                            if (dumpState.onTitlePrinted())
22996                                pw.println();
22997                            pw.println("AppOp Permissions:");
22998                        }
22999                        pw.print("  AppOp Permission ");
23000                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
23001                        pw.println(":");
23002                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
23003                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
23004                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
23005                        }
23006                    }
23007                }
23008            }
23009
23010            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
23011                boolean printedSomething = false;
23012                for (PackageParser.Provider p : mProviders.mProviders.values()) {
23013                    if (packageName != null && !packageName.equals(p.info.packageName)) {
23014                        continue;
23015                    }
23016                    if (!printedSomething) {
23017                        if (dumpState.onTitlePrinted())
23018                            pw.println();
23019                        pw.println("Registered ContentProviders:");
23020                        printedSomething = true;
23021                    }
23022                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
23023                    pw.print("    "); pw.println(p.toString());
23024                }
23025                printedSomething = false;
23026                for (Map.Entry<String, PackageParser.Provider> entry :
23027                        mProvidersByAuthority.entrySet()) {
23028                    PackageParser.Provider p = entry.getValue();
23029                    if (packageName != null && !packageName.equals(p.info.packageName)) {
23030                        continue;
23031                    }
23032                    if (!printedSomething) {
23033                        if (dumpState.onTitlePrinted())
23034                            pw.println();
23035                        pw.println("ContentProvider Authorities:");
23036                        printedSomething = true;
23037                    }
23038                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
23039                    pw.print("    "); pw.println(p.toString());
23040                    if (p.info != null && p.info.applicationInfo != null) {
23041                        final String appInfo = p.info.applicationInfo.toString();
23042                        pw.print("      applicationInfo="); pw.println(appInfo);
23043                    }
23044                }
23045            }
23046
23047            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
23048                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
23049            }
23050
23051            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
23052                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
23053            }
23054
23055            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
23056                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
23057            }
23058
23059            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
23060                if (dumpState.onTitlePrinted()) pw.println();
23061                pw.println("Package Changes:");
23062                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
23063                final int K = mChangedPackages.size();
23064                for (int i = 0; i < K; i++) {
23065                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
23066                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
23067                    final int N = changes.size();
23068                    if (N == 0) {
23069                        pw.print("    "); pw.println("No packages changed");
23070                    } else {
23071                        for (int j = 0; j < N; j++) {
23072                            final String pkgName = changes.valueAt(j);
23073                            final int sequenceNumber = changes.keyAt(j);
23074                            pw.print("    ");
23075                            pw.print("seq=");
23076                            pw.print(sequenceNumber);
23077                            pw.print(", package=");
23078                            pw.println(pkgName);
23079                        }
23080                    }
23081                }
23082            }
23083
23084            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
23085                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
23086            }
23087
23088            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
23089                // XXX should handle packageName != null by dumping only install data that
23090                // the given package is involved with.
23091                if (dumpState.onTitlePrinted()) pw.println();
23092
23093                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23094                ipw.println();
23095                ipw.println("Frozen packages:");
23096                ipw.increaseIndent();
23097                if (mFrozenPackages.size() == 0) {
23098                    ipw.println("(none)");
23099                } else {
23100                    for (int i = 0; i < mFrozenPackages.size(); i++) {
23101                        ipw.println(mFrozenPackages.valueAt(i));
23102                    }
23103                }
23104                ipw.decreaseIndent();
23105            }
23106
23107            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
23108                if (dumpState.onTitlePrinted()) pw.println();
23109
23110                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23111                ipw.println();
23112                ipw.println("Loaded volumes:");
23113                ipw.increaseIndent();
23114                if (mLoadedVolumes.size() == 0) {
23115                    ipw.println("(none)");
23116                } else {
23117                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
23118                        ipw.println(mLoadedVolumes.valueAt(i));
23119                    }
23120                }
23121                ipw.decreaseIndent();
23122            }
23123
23124            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
23125                if (dumpState.onTitlePrinted()) pw.println();
23126                dumpDexoptStateLPr(pw, packageName);
23127            }
23128
23129            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
23130                if (dumpState.onTitlePrinted()) pw.println();
23131                dumpCompilerStatsLPr(pw, packageName);
23132            }
23133
23134            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
23135                if (dumpState.onTitlePrinted()) pw.println();
23136                mSettings.dumpReadMessagesLPr(pw, dumpState);
23137
23138                pw.println();
23139                pw.println("Package warning messages:");
23140                BufferedReader in = null;
23141                String line = null;
23142                try {
23143                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23144                    while ((line = in.readLine()) != null) {
23145                        if (line.contains("ignored: updated version")) continue;
23146                        pw.println(line);
23147                    }
23148                } catch (IOException ignored) {
23149                } finally {
23150                    IoUtils.closeQuietly(in);
23151                }
23152            }
23153
23154            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
23155                BufferedReader in = null;
23156                String line = null;
23157                try {
23158                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23159                    while ((line = in.readLine()) != null) {
23160                        if (line.contains("ignored: updated version")) continue;
23161                        pw.print("msg,");
23162                        pw.println(line);
23163                    }
23164                } catch (IOException ignored) {
23165                } finally {
23166                    IoUtils.closeQuietly(in);
23167                }
23168            }
23169        }
23170
23171        // PackageInstaller should be called outside of mPackages lock
23172        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
23173            // XXX should handle packageName != null by dumping only install data that
23174            // the given package is involved with.
23175            if (dumpState.onTitlePrinted()) pw.println();
23176            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
23177        }
23178    }
23179
23180    private void dumpProto(FileDescriptor fd) {
23181        final ProtoOutputStream proto = new ProtoOutputStream(fd);
23182
23183        synchronized (mPackages) {
23184            final long requiredVerifierPackageToken =
23185                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
23186            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
23187            proto.write(
23188                    PackageServiceDumpProto.PackageShortProto.UID,
23189                    getPackageUid(
23190                            mRequiredVerifierPackage,
23191                            MATCH_DEBUG_TRIAGED_MISSING,
23192                            UserHandle.USER_SYSTEM));
23193            proto.end(requiredVerifierPackageToken);
23194
23195            if (mIntentFilterVerifierComponent != null) {
23196                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
23197                final long verifierPackageToken =
23198                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
23199                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
23200                proto.write(
23201                        PackageServiceDumpProto.PackageShortProto.UID,
23202                        getPackageUid(
23203                                verifierPackageName,
23204                                MATCH_DEBUG_TRIAGED_MISSING,
23205                                UserHandle.USER_SYSTEM));
23206                proto.end(verifierPackageToken);
23207            }
23208
23209            dumpSharedLibrariesProto(proto);
23210            dumpFeaturesProto(proto);
23211            mSettings.dumpPackagesProto(proto);
23212            mSettings.dumpSharedUsersProto(proto);
23213            dumpMessagesProto(proto);
23214        }
23215        proto.flush();
23216    }
23217
23218    private void dumpMessagesProto(ProtoOutputStream proto) {
23219        BufferedReader in = null;
23220        String line = null;
23221        try {
23222            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23223            while ((line = in.readLine()) != null) {
23224                if (line.contains("ignored: updated version")) continue;
23225                proto.write(PackageServiceDumpProto.MESSAGES, line);
23226            }
23227        } catch (IOException ignored) {
23228        } finally {
23229            IoUtils.closeQuietly(in);
23230        }
23231    }
23232
23233    private void dumpFeaturesProto(ProtoOutputStream proto) {
23234        synchronized (mAvailableFeatures) {
23235            final int count = mAvailableFeatures.size();
23236            for (int i = 0; i < count; i++) {
23237                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
23238                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
23239                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
23240                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
23241                proto.end(featureToken);
23242            }
23243        }
23244    }
23245
23246    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
23247        final int count = mSharedLibraries.size();
23248        for (int i = 0; i < count; i++) {
23249            final String libName = mSharedLibraries.keyAt(i);
23250            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
23251            if (versionedLib == null) {
23252                continue;
23253            }
23254            final int versionCount = versionedLib.size();
23255            for (int j = 0; j < versionCount; j++) {
23256                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23257                final long sharedLibraryToken =
23258                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23259                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23260                final boolean isJar = (libEntry.path != null);
23261                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23262                if (isJar) {
23263                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23264                } else {
23265                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23266                }
23267                proto.end(sharedLibraryToken);
23268            }
23269        }
23270    }
23271
23272    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23273        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23274        ipw.println();
23275        ipw.println("Dexopt state:");
23276        ipw.increaseIndent();
23277        Collection<PackageParser.Package> packages = null;
23278        if (packageName != null) {
23279            PackageParser.Package targetPackage = mPackages.get(packageName);
23280            if (targetPackage != null) {
23281                packages = Collections.singletonList(targetPackage);
23282            } else {
23283                ipw.println("Unable to find package: " + packageName);
23284                return;
23285            }
23286        } else {
23287            packages = mPackages.values();
23288        }
23289
23290        for (PackageParser.Package pkg : packages) {
23291            ipw.println("[" + pkg.packageName + "]");
23292            ipw.increaseIndent();
23293            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23294                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23295            ipw.decreaseIndent();
23296        }
23297    }
23298
23299    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23300        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23301        ipw.println();
23302        ipw.println("Compiler stats:");
23303        ipw.increaseIndent();
23304        Collection<PackageParser.Package> packages = null;
23305        if (packageName != null) {
23306            PackageParser.Package targetPackage = mPackages.get(packageName);
23307            if (targetPackage != null) {
23308                packages = Collections.singletonList(targetPackage);
23309            } else {
23310                ipw.println("Unable to find package: " + packageName);
23311                return;
23312            }
23313        } else {
23314            packages = mPackages.values();
23315        }
23316
23317        for (PackageParser.Package pkg : packages) {
23318            ipw.println("[" + pkg.packageName + "]");
23319            ipw.increaseIndent();
23320
23321            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23322            if (stats == null) {
23323                ipw.println("(No recorded stats)");
23324            } else {
23325                stats.dump(ipw);
23326            }
23327            ipw.decreaseIndent();
23328        }
23329    }
23330
23331    private String dumpDomainString(String packageName) {
23332        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23333                .getList();
23334        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23335
23336        ArraySet<String> result = new ArraySet<>();
23337        if (iviList.size() > 0) {
23338            for (IntentFilterVerificationInfo ivi : iviList) {
23339                for (String host : ivi.getDomains()) {
23340                    result.add(host);
23341                }
23342            }
23343        }
23344        if (filters != null && filters.size() > 0) {
23345            for (IntentFilter filter : filters) {
23346                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23347                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23348                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23349                    result.addAll(filter.getHostsList());
23350                }
23351            }
23352        }
23353
23354        StringBuilder sb = new StringBuilder(result.size() * 16);
23355        for (String domain : result) {
23356            if (sb.length() > 0) sb.append(" ");
23357            sb.append(domain);
23358        }
23359        return sb.toString();
23360    }
23361
23362    // ------- apps on sdcard specific code -------
23363    static final boolean DEBUG_SD_INSTALL = false;
23364
23365    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23366
23367    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23368
23369    private boolean mMediaMounted = false;
23370
23371    static String getEncryptKey() {
23372        try {
23373            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23374                    SD_ENCRYPTION_KEYSTORE_NAME);
23375            if (sdEncKey == null) {
23376                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23377                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23378                if (sdEncKey == null) {
23379                    Slog.e(TAG, "Failed to create encryption keys");
23380                    return null;
23381                }
23382            }
23383            return sdEncKey;
23384        } catch (NoSuchAlgorithmException nsae) {
23385            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23386            return null;
23387        } catch (IOException ioe) {
23388            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23389            return null;
23390        }
23391    }
23392
23393    /*
23394     * Update media status on PackageManager.
23395     */
23396    @Override
23397    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23398        enforceSystemOrRoot("Media status can only be updated by the system");
23399        // reader; this apparently protects mMediaMounted, but should probably
23400        // be a different lock in that case.
23401        synchronized (mPackages) {
23402            Log.i(TAG, "Updating external media status from "
23403                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23404                    + (mediaStatus ? "mounted" : "unmounted"));
23405            if (DEBUG_SD_INSTALL)
23406                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23407                        + ", mMediaMounted=" + mMediaMounted);
23408            if (mediaStatus == mMediaMounted) {
23409                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23410                        : 0, -1);
23411                mHandler.sendMessage(msg);
23412                return;
23413            }
23414            mMediaMounted = mediaStatus;
23415        }
23416        // Queue up an async operation since the package installation may take a
23417        // little while.
23418        mHandler.post(new Runnable() {
23419            public void run() {
23420                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23421            }
23422        });
23423    }
23424
23425    /**
23426     * Called by StorageManagerService when the initial ASECs to scan are available.
23427     * Should block until all the ASEC containers are finished being scanned.
23428     */
23429    public void scanAvailableAsecs() {
23430        updateExternalMediaStatusInner(true, false, false);
23431    }
23432
23433    /*
23434     * Collect information of applications on external media, map them against
23435     * existing containers and update information based on current mount status.
23436     * Please note that we always have to report status if reportStatus has been
23437     * set to true especially when unloading packages.
23438     */
23439    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23440            boolean externalStorage) {
23441        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23442        int[] uidArr = EmptyArray.INT;
23443
23444        final String[] list = PackageHelper.getSecureContainerList();
23445        if (ArrayUtils.isEmpty(list)) {
23446            Log.i(TAG, "No secure containers found");
23447        } else {
23448            // Process list of secure containers and categorize them
23449            // as active or stale based on their package internal state.
23450
23451            // reader
23452            synchronized (mPackages) {
23453                for (String cid : list) {
23454                    // Leave stages untouched for now; installer service owns them
23455                    if (PackageInstallerService.isStageName(cid)) continue;
23456
23457                    if (DEBUG_SD_INSTALL)
23458                        Log.i(TAG, "Processing container " + cid);
23459                    String pkgName = getAsecPackageName(cid);
23460                    if (pkgName == null) {
23461                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23462                        continue;
23463                    }
23464                    if (DEBUG_SD_INSTALL)
23465                        Log.i(TAG, "Looking for pkg : " + pkgName);
23466
23467                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23468                    if (ps == null) {
23469                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23470                        continue;
23471                    }
23472
23473                    /*
23474                     * Skip packages that are not external if we're unmounting
23475                     * external storage.
23476                     */
23477                    if (externalStorage && !isMounted && !isExternal(ps)) {
23478                        continue;
23479                    }
23480
23481                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23482                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23483                    // The package status is changed only if the code path
23484                    // matches between settings and the container id.
23485                    if (ps.codePathString != null
23486                            && ps.codePathString.startsWith(args.getCodePath())) {
23487                        if (DEBUG_SD_INSTALL) {
23488                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23489                                    + " at code path: " + ps.codePathString);
23490                        }
23491
23492                        // We do have a valid package installed on sdcard
23493                        processCids.put(args, ps.codePathString);
23494                        final int uid = ps.appId;
23495                        if (uid != -1) {
23496                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23497                        }
23498                    } else {
23499                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23500                                + ps.codePathString);
23501                    }
23502                }
23503            }
23504
23505            Arrays.sort(uidArr);
23506        }
23507
23508        // Process packages with valid entries.
23509        if (isMounted) {
23510            if (DEBUG_SD_INSTALL)
23511                Log.i(TAG, "Loading packages");
23512            loadMediaPackages(processCids, uidArr, externalStorage);
23513            startCleaningPackages();
23514            mInstallerService.onSecureContainersAvailable();
23515        } else {
23516            if (DEBUG_SD_INSTALL)
23517                Log.i(TAG, "Unloading packages");
23518            unloadMediaPackages(processCids, uidArr, reportStatus);
23519        }
23520    }
23521
23522    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23523            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23524        final int size = infos.size();
23525        final String[] packageNames = new String[size];
23526        final int[] packageUids = new int[size];
23527        for (int i = 0; i < size; i++) {
23528            final ApplicationInfo info = infos.get(i);
23529            packageNames[i] = info.packageName;
23530            packageUids[i] = info.uid;
23531        }
23532        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23533                finishedReceiver);
23534    }
23535
23536    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23537            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23538        sendResourcesChangedBroadcast(mediaStatus, replacing,
23539                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23540    }
23541
23542    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23543            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23544        int size = pkgList.length;
23545        if (size > 0) {
23546            // Send broadcasts here
23547            Bundle extras = new Bundle();
23548            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23549            if (uidArr != null) {
23550                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23551            }
23552            if (replacing) {
23553                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23554            }
23555            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23556                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23557            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23558        }
23559    }
23560
23561   /*
23562     * Look at potentially valid container ids from processCids If package
23563     * information doesn't match the one on record or package scanning fails,
23564     * the cid is added to list of removeCids. We currently don't delete stale
23565     * containers.
23566     */
23567    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23568            boolean externalStorage) {
23569        ArrayList<String> pkgList = new ArrayList<String>();
23570        Set<AsecInstallArgs> keys = processCids.keySet();
23571
23572        for (AsecInstallArgs args : keys) {
23573            String codePath = processCids.get(args);
23574            if (DEBUG_SD_INSTALL)
23575                Log.i(TAG, "Loading container : " + args.cid);
23576            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23577            try {
23578                // Make sure there are no container errors first.
23579                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23580                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23581                            + " when installing from sdcard");
23582                    continue;
23583                }
23584                // Check code path here.
23585                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23586                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23587                            + " does not match one in settings " + codePath);
23588                    continue;
23589                }
23590                // Parse package
23591                int parseFlags = mDefParseFlags;
23592                if (args.isExternalAsec()) {
23593                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23594                }
23595                if (args.isFwdLocked()) {
23596                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23597                }
23598
23599                synchronized (mInstallLock) {
23600                    PackageParser.Package pkg = null;
23601                    try {
23602                        // Sadly we don't know the package name yet to freeze it
23603                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23604                                SCAN_IGNORE_FROZEN, 0, null);
23605                    } catch (PackageManagerException e) {
23606                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23607                    }
23608                    // Scan the package
23609                    if (pkg != null) {
23610                        /*
23611                         * TODO why is the lock being held? doPostInstall is
23612                         * called in other places without the lock. This needs
23613                         * to be straightened out.
23614                         */
23615                        // writer
23616                        synchronized (mPackages) {
23617                            retCode = PackageManager.INSTALL_SUCCEEDED;
23618                            pkgList.add(pkg.packageName);
23619                            // Post process args
23620                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23621                                    pkg.applicationInfo.uid);
23622                        }
23623                    } else {
23624                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23625                    }
23626                }
23627
23628            } finally {
23629                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23630                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23631                }
23632            }
23633        }
23634        // writer
23635        synchronized (mPackages) {
23636            // If the platform SDK has changed since the last time we booted,
23637            // we need to re-grant app permission to catch any new ones that
23638            // appear. This is really a hack, and means that apps can in some
23639            // cases get permissions that the user didn't initially explicitly
23640            // allow... it would be nice to have some better way to handle
23641            // this situation.
23642            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23643                    : mSettings.getInternalVersion();
23644            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23645                    : StorageManager.UUID_PRIVATE_INTERNAL;
23646
23647            int updateFlags = UPDATE_PERMISSIONS_ALL;
23648            if (ver.sdkVersion != mSdkVersion) {
23649                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23650                        + mSdkVersion + "; regranting permissions for external");
23651                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23652            }
23653            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23654
23655            // Yay, everything is now upgraded
23656            ver.forceCurrent();
23657
23658            // can downgrade to reader
23659            // Persist settings
23660            mSettings.writeLPr();
23661        }
23662        // Send a broadcast to let everyone know we are done processing
23663        if (pkgList.size() > 0) {
23664            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23665        }
23666    }
23667
23668   /*
23669     * Utility method to unload a list of specified containers
23670     */
23671    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23672        // Just unmount all valid containers.
23673        for (AsecInstallArgs arg : cidArgs) {
23674            synchronized (mInstallLock) {
23675                arg.doPostDeleteLI(false);
23676           }
23677       }
23678   }
23679
23680    /*
23681     * Unload packages mounted on external media. This involves deleting package
23682     * data from internal structures, sending broadcasts about disabled packages,
23683     * gc'ing to free up references, unmounting all secure containers
23684     * corresponding to packages on external media, and posting a
23685     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23686     * that we always have to post this message if status has been requested no
23687     * matter what.
23688     */
23689    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23690            final boolean reportStatus) {
23691        if (DEBUG_SD_INSTALL)
23692            Log.i(TAG, "unloading media packages");
23693        ArrayList<String> pkgList = new ArrayList<String>();
23694        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23695        final Set<AsecInstallArgs> keys = processCids.keySet();
23696        for (AsecInstallArgs args : keys) {
23697            String pkgName = args.getPackageName();
23698            if (DEBUG_SD_INSTALL)
23699                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23700            // Delete package internally
23701            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23702            synchronized (mInstallLock) {
23703                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23704                final boolean res;
23705                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23706                        "unloadMediaPackages")) {
23707                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23708                            null);
23709                }
23710                if (res) {
23711                    pkgList.add(pkgName);
23712                } else {
23713                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23714                    failedList.add(args);
23715                }
23716            }
23717        }
23718
23719        // reader
23720        synchronized (mPackages) {
23721            // We didn't update the settings after removing each package;
23722            // write them now for all packages.
23723            mSettings.writeLPr();
23724        }
23725
23726        // We have to absolutely send UPDATED_MEDIA_STATUS only
23727        // after confirming that all the receivers processed the ordered
23728        // broadcast when packages get disabled, force a gc to clean things up.
23729        // and unload all the containers.
23730        if (pkgList.size() > 0) {
23731            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23732                    new IIntentReceiver.Stub() {
23733                public void performReceive(Intent intent, int resultCode, String data,
23734                        Bundle extras, boolean ordered, boolean sticky,
23735                        int sendingUser) throws RemoteException {
23736                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23737                            reportStatus ? 1 : 0, 1, keys);
23738                    mHandler.sendMessage(msg);
23739                }
23740            });
23741        } else {
23742            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23743                    keys);
23744            mHandler.sendMessage(msg);
23745        }
23746    }
23747
23748    private void loadPrivatePackages(final VolumeInfo vol) {
23749        mHandler.post(new Runnable() {
23750            @Override
23751            public void run() {
23752                loadPrivatePackagesInner(vol);
23753            }
23754        });
23755    }
23756
23757    private void loadPrivatePackagesInner(VolumeInfo vol) {
23758        final String volumeUuid = vol.fsUuid;
23759        if (TextUtils.isEmpty(volumeUuid)) {
23760            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23761            return;
23762        }
23763
23764        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23765        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23766        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23767
23768        final VersionInfo ver;
23769        final List<PackageSetting> packages;
23770        synchronized (mPackages) {
23771            ver = mSettings.findOrCreateVersion(volumeUuid);
23772            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23773        }
23774
23775        for (PackageSetting ps : packages) {
23776            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23777            synchronized (mInstallLock) {
23778                final PackageParser.Package pkg;
23779                try {
23780                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23781                    loaded.add(pkg.applicationInfo);
23782
23783                } catch (PackageManagerException e) {
23784                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23785                }
23786
23787                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23788                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23789                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23790                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23791                }
23792            }
23793        }
23794
23795        // Reconcile app data for all started/unlocked users
23796        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23797        final UserManager um = mContext.getSystemService(UserManager.class);
23798        UserManagerInternal umInternal = getUserManagerInternal();
23799        for (UserInfo user : um.getUsers()) {
23800            final int flags;
23801            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23802                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23803            } else if (umInternal.isUserRunning(user.id)) {
23804                flags = StorageManager.FLAG_STORAGE_DE;
23805            } else {
23806                continue;
23807            }
23808
23809            try {
23810                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23811                synchronized (mInstallLock) {
23812                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23813                }
23814            } catch (IllegalStateException e) {
23815                // Device was probably ejected, and we'll process that event momentarily
23816                Slog.w(TAG, "Failed to prepare storage: " + e);
23817            }
23818        }
23819
23820        synchronized (mPackages) {
23821            int updateFlags = UPDATE_PERMISSIONS_ALL;
23822            if (ver.sdkVersion != mSdkVersion) {
23823                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23824                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23825                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23826            }
23827            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23828
23829            // Yay, everything is now upgraded
23830            ver.forceCurrent();
23831
23832            mSettings.writeLPr();
23833        }
23834
23835        for (PackageFreezer freezer : freezers) {
23836            freezer.close();
23837        }
23838
23839        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23840        sendResourcesChangedBroadcast(true, false, loaded, null);
23841        mLoadedVolumes.add(vol.getId());
23842    }
23843
23844    private void unloadPrivatePackages(final VolumeInfo vol) {
23845        mHandler.post(new Runnable() {
23846            @Override
23847            public void run() {
23848                unloadPrivatePackagesInner(vol);
23849            }
23850        });
23851    }
23852
23853    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23854        final String volumeUuid = vol.fsUuid;
23855        if (TextUtils.isEmpty(volumeUuid)) {
23856            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23857            return;
23858        }
23859
23860        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23861        synchronized (mInstallLock) {
23862        synchronized (mPackages) {
23863            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23864            for (PackageSetting ps : packages) {
23865                if (ps.pkg == null) continue;
23866
23867                final ApplicationInfo info = ps.pkg.applicationInfo;
23868                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23869                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23870
23871                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23872                        "unloadPrivatePackagesInner")) {
23873                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23874                            false, null)) {
23875                        unloaded.add(info);
23876                    } else {
23877                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23878                    }
23879                }
23880
23881                // Try very hard to release any references to this package
23882                // so we don't risk the system server being killed due to
23883                // open FDs
23884                AttributeCache.instance().removePackage(ps.name);
23885            }
23886
23887            mSettings.writeLPr();
23888        }
23889        }
23890
23891        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23892        sendResourcesChangedBroadcast(false, false, unloaded, null);
23893        mLoadedVolumes.remove(vol.getId());
23894
23895        // Try very hard to release any references to this path so we don't risk
23896        // the system server being killed due to open FDs
23897        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23898
23899        for (int i = 0; i < 3; i++) {
23900            System.gc();
23901            System.runFinalization();
23902        }
23903    }
23904
23905    private void assertPackageKnown(String volumeUuid, String packageName)
23906            throws PackageManagerException {
23907        synchronized (mPackages) {
23908            // Normalize package name to handle renamed packages
23909            packageName = normalizePackageNameLPr(packageName);
23910
23911            final PackageSetting ps = mSettings.mPackages.get(packageName);
23912            if (ps == null) {
23913                throw new PackageManagerException("Package " + packageName + " is unknown");
23914            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23915                throw new PackageManagerException(
23916                        "Package " + packageName + " found on unknown volume " + volumeUuid
23917                                + "; expected volume " + ps.volumeUuid);
23918            }
23919        }
23920    }
23921
23922    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23923            throws PackageManagerException {
23924        synchronized (mPackages) {
23925            // Normalize package name to handle renamed packages
23926            packageName = normalizePackageNameLPr(packageName);
23927
23928            final PackageSetting ps = mSettings.mPackages.get(packageName);
23929            if (ps == null) {
23930                throw new PackageManagerException("Package " + packageName + " is unknown");
23931            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23932                throw new PackageManagerException(
23933                        "Package " + packageName + " found on unknown volume " + volumeUuid
23934                                + "; expected volume " + ps.volumeUuid);
23935            } else if (!ps.getInstalled(userId)) {
23936                throw new PackageManagerException(
23937                        "Package " + packageName + " not installed for user " + userId);
23938            }
23939        }
23940    }
23941
23942    private List<String> collectAbsoluteCodePaths() {
23943        synchronized (mPackages) {
23944            List<String> codePaths = new ArrayList<>();
23945            final int packageCount = mSettings.mPackages.size();
23946            for (int i = 0; i < packageCount; i++) {
23947                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23948                codePaths.add(ps.codePath.getAbsolutePath());
23949            }
23950            return codePaths;
23951        }
23952    }
23953
23954    /**
23955     * Examine all apps present on given mounted volume, and destroy apps that
23956     * aren't expected, either due to uninstallation or reinstallation on
23957     * another volume.
23958     */
23959    private void reconcileApps(String volumeUuid) {
23960        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23961        List<File> filesToDelete = null;
23962
23963        final File[] files = FileUtils.listFilesOrEmpty(
23964                Environment.getDataAppDirectory(volumeUuid));
23965        for (File file : files) {
23966            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23967                    && !PackageInstallerService.isStageName(file.getName());
23968            if (!isPackage) {
23969                // Ignore entries which are not packages
23970                continue;
23971            }
23972
23973            String absolutePath = file.getAbsolutePath();
23974
23975            boolean pathValid = false;
23976            final int absoluteCodePathCount = absoluteCodePaths.size();
23977            for (int i = 0; i < absoluteCodePathCount; i++) {
23978                String absoluteCodePath = absoluteCodePaths.get(i);
23979                if (absolutePath.startsWith(absoluteCodePath)) {
23980                    pathValid = true;
23981                    break;
23982                }
23983            }
23984
23985            if (!pathValid) {
23986                if (filesToDelete == null) {
23987                    filesToDelete = new ArrayList<>();
23988                }
23989                filesToDelete.add(file);
23990            }
23991        }
23992
23993        if (filesToDelete != null) {
23994            final int fileToDeleteCount = filesToDelete.size();
23995            for (int i = 0; i < fileToDeleteCount; i++) {
23996                File fileToDelete = filesToDelete.get(i);
23997                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23998                synchronized (mInstallLock) {
23999                    removeCodePathLI(fileToDelete);
24000                }
24001            }
24002        }
24003    }
24004
24005    /**
24006     * Reconcile all app data for the given user.
24007     * <p>
24008     * Verifies that directories exist and that ownership and labeling is
24009     * correct for all installed apps on all mounted volumes.
24010     */
24011    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
24012        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24013        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
24014            final String volumeUuid = vol.getFsUuid();
24015            synchronized (mInstallLock) {
24016                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
24017            }
24018        }
24019    }
24020
24021    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
24022            boolean migrateAppData) {
24023        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
24024    }
24025
24026    /**
24027     * Reconcile all app data on given mounted volume.
24028     * <p>
24029     * Destroys app data that isn't expected, either due to uninstallation or
24030     * reinstallation on another volume.
24031     * <p>
24032     * Verifies that directories exist and that ownership and labeling is
24033     * correct for all installed apps.
24034     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
24035     */
24036    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
24037            boolean migrateAppData, boolean onlyCoreApps) {
24038        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
24039                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
24040        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
24041
24042        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
24043        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
24044
24045        // First look for stale data that doesn't belong, and check if things
24046        // have changed since we did our last restorecon
24047        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24048            if (StorageManager.isFileEncryptedNativeOrEmulated()
24049                    && !StorageManager.isUserKeyUnlocked(userId)) {
24050                throw new RuntimeException(
24051                        "Yikes, someone asked us to reconcile CE storage while " + userId
24052                                + " was still locked; this would have caused massive data loss!");
24053            }
24054
24055            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
24056            for (File file : files) {
24057                final String packageName = file.getName();
24058                try {
24059                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24060                } catch (PackageManagerException e) {
24061                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24062                    try {
24063                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24064                                StorageManager.FLAG_STORAGE_CE, 0);
24065                    } catch (InstallerException e2) {
24066                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24067                    }
24068                }
24069            }
24070        }
24071        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
24072            final File[] files = FileUtils.listFilesOrEmpty(deDir);
24073            for (File file : files) {
24074                final String packageName = file.getName();
24075                try {
24076                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24077                } catch (PackageManagerException e) {
24078                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24079                    try {
24080                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24081                                StorageManager.FLAG_STORAGE_DE, 0);
24082                    } catch (InstallerException e2) {
24083                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24084                    }
24085                }
24086            }
24087        }
24088
24089        // Ensure that data directories are ready to roll for all packages
24090        // installed for this volume and user
24091        final List<PackageSetting> packages;
24092        synchronized (mPackages) {
24093            packages = mSettings.getVolumePackagesLPr(volumeUuid);
24094        }
24095        int preparedCount = 0;
24096        for (PackageSetting ps : packages) {
24097            final String packageName = ps.name;
24098            if (ps.pkg == null) {
24099                Slog.w(TAG, "Odd, missing scanned package " + packageName);
24100                // TODO: might be due to legacy ASEC apps; we should circle back
24101                // and reconcile again once they're scanned
24102                continue;
24103            }
24104            // Skip non-core apps if requested
24105            if (onlyCoreApps && !ps.pkg.coreApp) {
24106                result.add(packageName);
24107                continue;
24108            }
24109
24110            if (ps.getInstalled(userId)) {
24111                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
24112                preparedCount++;
24113            }
24114        }
24115
24116        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
24117        return result;
24118    }
24119
24120    /**
24121     * Prepare app data for the given app just after it was installed or
24122     * upgraded. This method carefully only touches users that it's installed
24123     * for, and it forces a restorecon to handle any seinfo changes.
24124     * <p>
24125     * Verifies that directories exist and that ownership and labeling is
24126     * correct for all installed apps. If there is an ownership mismatch, it
24127     * will try recovering system apps by wiping data; third-party app data is
24128     * left intact.
24129     * <p>
24130     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
24131     */
24132    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
24133        final PackageSetting ps;
24134        synchronized (mPackages) {
24135            ps = mSettings.mPackages.get(pkg.packageName);
24136            mSettings.writeKernelMappingLPr(ps);
24137        }
24138
24139        final UserManager um = mContext.getSystemService(UserManager.class);
24140        UserManagerInternal umInternal = getUserManagerInternal();
24141        for (UserInfo user : um.getUsers()) {
24142            final int flags;
24143            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
24144                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
24145            } else if (umInternal.isUserRunning(user.id)) {
24146                flags = StorageManager.FLAG_STORAGE_DE;
24147            } else {
24148                continue;
24149            }
24150
24151            if (ps.getInstalled(user.id)) {
24152                // TODO: when user data is locked, mark that we're still dirty
24153                prepareAppDataLIF(pkg, user.id, flags);
24154            }
24155        }
24156    }
24157
24158    /**
24159     * Prepare app data for the given app.
24160     * <p>
24161     * Verifies that directories exist and that ownership and labeling is
24162     * correct for all installed apps. If there is an ownership mismatch, this
24163     * will try recovering system apps by wiping data; third-party app data is
24164     * left intact.
24165     */
24166    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
24167        if (pkg == null) {
24168            Slog.wtf(TAG, "Package was null!", new Throwable());
24169            return;
24170        }
24171        prepareAppDataLeafLIF(pkg, userId, flags);
24172        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24173        for (int i = 0; i < childCount; i++) {
24174            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
24175        }
24176    }
24177
24178    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
24179            boolean maybeMigrateAppData) {
24180        prepareAppDataLIF(pkg, userId, flags);
24181
24182        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
24183            // We may have just shuffled around app data directories, so
24184            // prepare them one more time
24185            prepareAppDataLIF(pkg, userId, flags);
24186        }
24187    }
24188
24189    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24190        if (DEBUG_APP_DATA) {
24191            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
24192                    + Integer.toHexString(flags));
24193        }
24194
24195        final String volumeUuid = pkg.volumeUuid;
24196        final String packageName = pkg.packageName;
24197        final ApplicationInfo app = pkg.applicationInfo;
24198        final int appId = UserHandle.getAppId(app.uid);
24199
24200        Preconditions.checkNotNull(app.seInfo);
24201
24202        long ceDataInode = -1;
24203        try {
24204            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24205                    appId, app.seInfo, app.targetSdkVersion);
24206        } catch (InstallerException e) {
24207            if (app.isSystemApp()) {
24208                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
24209                        + ", but trying to recover: " + e);
24210                destroyAppDataLeafLIF(pkg, userId, flags);
24211                try {
24212                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24213                            appId, app.seInfo, app.targetSdkVersion);
24214                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
24215                } catch (InstallerException e2) {
24216                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
24217                }
24218            } else {
24219                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
24220            }
24221        }
24222
24223        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
24224            // TODO: mark this structure as dirty so we persist it!
24225            synchronized (mPackages) {
24226                final PackageSetting ps = mSettings.mPackages.get(packageName);
24227                if (ps != null) {
24228                    ps.setCeDataInode(ceDataInode, userId);
24229                }
24230            }
24231        }
24232
24233        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24234    }
24235
24236    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
24237        if (pkg == null) {
24238            Slog.wtf(TAG, "Package was null!", new Throwable());
24239            return;
24240        }
24241        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24242        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24243        for (int i = 0; i < childCount; i++) {
24244            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
24245        }
24246    }
24247
24248    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24249        final String volumeUuid = pkg.volumeUuid;
24250        final String packageName = pkg.packageName;
24251        final ApplicationInfo app = pkg.applicationInfo;
24252
24253        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24254            // Create a native library symlink only if we have native libraries
24255            // and if the native libraries are 32 bit libraries. We do not provide
24256            // this symlink for 64 bit libraries.
24257            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24258                final String nativeLibPath = app.nativeLibraryDir;
24259                try {
24260                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24261                            nativeLibPath, userId);
24262                } catch (InstallerException e) {
24263                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24264                }
24265            }
24266        }
24267    }
24268
24269    /**
24270     * For system apps on non-FBE devices, this method migrates any existing
24271     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24272     * requested by the app.
24273     */
24274    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24275        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24276                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24277            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24278                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24279            try {
24280                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24281                        storageTarget);
24282            } catch (InstallerException e) {
24283                logCriticalInfo(Log.WARN,
24284                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24285            }
24286            return true;
24287        } else {
24288            return false;
24289        }
24290    }
24291
24292    public PackageFreezer freezePackage(String packageName, String killReason) {
24293        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24294    }
24295
24296    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24297        return new PackageFreezer(packageName, userId, killReason);
24298    }
24299
24300    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24301            String killReason) {
24302        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24303    }
24304
24305    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24306            String killReason) {
24307        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24308            return new PackageFreezer();
24309        } else {
24310            return freezePackage(packageName, userId, killReason);
24311        }
24312    }
24313
24314    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24315            String killReason) {
24316        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24317    }
24318
24319    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24320            String killReason) {
24321        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24322            return new PackageFreezer();
24323        } else {
24324            return freezePackage(packageName, userId, killReason);
24325        }
24326    }
24327
24328    /**
24329     * Class that freezes and kills the given package upon creation, and
24330     * unfreezes it upon closing. This is typically used when doing surgery on
24331     * app code/data to prevent the app from running while you're working.
24332     */
24333    private class PackageFreezer implements AutoCloseable {
24334        private final String mPackageName;
24335        private final PackageFreezer[] mChildren;
24336
24337        private final boolean mWeFroze;
24338
24339        private final AtomicBoolean mClosed = new AtomicBoolean();
24340        private final CloseGuard mCloseGuard = CloseGuard.get();
24341
24342        /**
24343         * Create and return a stub freezer that doesn't actually do anything,
24344         * typically used when someone requested
24345         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24346         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24347         */
24348        public PackageFreezer() {
24349            mPackageName = null;
24350            mChildren = null;
24351            mWeFroze = false;
24352            mCloseGuard.open("close");
24353        }
24354
24355        public PackageFreezer(String packageName, int userId, String killReason) {
24356            synchronized (mPackages) {
24357                mPackageName = packageName;
24358                mWeFroze = mFrozenPackages.add(mPackageName);
24359
24360                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24361                if (ps != null) {
24362                    killApplication(ps.name, ps.appId, userId, killReason);
24363                }
24364
24365                final PackageParser.Package p = mPackages.get(packageName);
24366                if (p != null && p.childPackages != null) {
24367                    final int N = p.childPackages.size();
24368                    mChildren = new PackageFreezer[N];
24369                    for (int i = 0; i < N; i++) {
24370                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24371                                userId, killReason);
24372                    }
24373                } else {
24374                    mChildren = null;
24375                }
24376            }
24377            mCloseGuard.open("close");
24378        }
24379
24380        @Override
24381        protected void finalize() throws Throwable {
24382            try {
24383                if (mCloseGuard != null) {
24384                    mCloseGuard.warnIfOpen();
24385                }
24386
24387                close();
24388            } finally {
24389                super.finalize();
24390            }
24391        }
24392
24393        @Override
24394        public void close() {
24395            mCloseGuard.close();
24396            if (mClosed.compareAndSet(false, true)) {
24397                synchronized (mPackages) {
24398                    if (mWeFroze) {
24399                        mFrozenPackages.remove(mPackageName);
24400                    }
24401
24402                    if (mChildren != null) {
24403                        for (PackageFreezer freezer : mChildren) {
24404                            freezer.close();
24405                        }
24406                    }
24407                }
24408            }
24409        }
24410    }
24411
24412    /**
24413     * Verify that given package is currently frozen.
24414     */
24415    private void checkPackageFrozen(String packageName) {
24416        synchronized (mPackages) {
24417            if (!mFrozenPackages.contains(packageName)) {
24418                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24419            }
24420        }
24421    }
24422
24423    @Override
24424    public int movePackage(final String packageName, final String volumeUuid) {
24425        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24426
24427        final int callingUid = Binder.getCallingUid();
24428        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24429        final int moveId = mNextMoveId.getAndIncrement();
24430        mHandler.post(new Runnable() {
24431            @Override
24432            public void run() {
24433                try {
24434                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24435                } catch (PackageManagerException e) {
24436                    Slog.w(TAG, "Failed to move " + packageName, e);
24437                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24438                }
24439            }
24440        });
24441        return moveId;
24442    }
24443
24444    private void movePackageInternal(final String packageName, final String volumeUuid,
24445            final int moveId, final int callingUid, UserHandle user)
24446                    throws PackageManagerException {
24447        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24448        final PackageManager pm = mContext.getPackageManager();
24449
24450        final boolean currentAsec;
24451        final String currentVolumeUuid;
24452        final File codeFile;
24453        final String installerPackageName;
24454        final String packageAbiOverride;
24455        final int appId;
24456        final String seinfo;
24457        final String label;
24458        final int targetSdkVersion;
24459        final PackageFreezer freezer;
24460        final int[] installedUserIds;
24461
24462        // reader
24463        synchronized (mPackages) {
24464            final PackageParser.Package pkg = mPackages.get(packageName);
24465            final PackageSetting ps = mSettings.mPackages.get(packageName);
24466            if (pkg == null
24467                    || ps == null
24468                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24469                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24470            }
24471            if (pkg.applicationInfo.isSystemApp()) {
24472                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24473                        "Cannot move system application");
24474            }
24475
24476            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24477            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24478                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24479            if (isInternalStorage && !allow3rdPartyOnInternal) {
24480                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24481                        "3rd party apps are not allowed on internal storage");
24482            }
24483
24484            if (pkg.applicationInfo.isExternalAsec()) {
24485                currentAsec = true;
24486                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24487            } else if (pkg.applicationInfo.isForwardLocked()) {
24488                currentAsec = true;
24489                currentVolumeUuid = "forward_locked";
24490            } else {
24491                currentAsec = false;
24492                currentVolumeUuid = ps.volumeUuid;
24493
24494                final File probe = new File(pkg.codePath);
24495                final File probeOat = new File(probe, "oat");
24496                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24497                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24498                            "Move only supported for modern cluster style installs");
24499                }
24500            }
24501
24502            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24503                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24504                        "Package already moved to " + volumeUuid);
24505            }
24506            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24507                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24508                        "Device admin cannot be moved");
24509            }
24510
24511            if (mFrozenPackages.contains(packageName)) {
24512                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24513                        "Failed to move already frozen package");
24514            }
24515
24516            codeFile = new File(pkg.codePath);
24517            installerPackageName = ps.installerPackageName;
24518            packageAbiOverride = ps.cpuAbiOverrideString;
24519            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24520            seinfo = pkg.applicationInfo.seInfo;
24521            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24522            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24523            freezer = freezePackage(packageName, "movePackageInternal");
24524            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24525        }
24526
24527        final Bundle extras = new Bundle();
24528        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24529        extras.putString(Intent.EXTRA_TITLE, label);
24530        mMoveCallbacks.notifyCreated(moveId, extras);
24531
24532        int installFlags;
24533        final boolean moveCompleteApp;
24534        final File measurePath;
24535
24536        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24537            installFlags = INSTALL_INTERNAL;
24538            moveCompleteApp = !currentAsec;
24539            measurePath = Environment.getDataAppDirectory(volumeUuid);
24540        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24541            installFlags = INSTALL_EXTERNAL;
24542            moveCompleteApp = false;
24543            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24544        } else {
24545            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24546            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24547                    || !volume.isMountedWritable()) {
24548                freezer.close();
24549                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24550                        "Move location not mounted private volume");
24551            }
24552
24553            Preconditions.checkState(!currentAsec);
24554
24555            installFlags = INSTALL_INTERNAL;
24556            moveCompleteApp = true;
24557            measurePath = Environment.getDataAppDirectory(volumeUuid);
24558        }
24559
24560        // If we're moving app data around, we need all the users unlocked
24561        if (moveCompleteApp) {
24562            for (int userId : installedUserIds) {
24563                if (StorageManager.isFileEncryptedNativeOrEmulated()
24564                        && !StorageManager.isUserKeyUnlocked(userId)) {
24565                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24566                            "User " + userId + " must be unlocked");
24567                }
24568            }
24569        }
24570
24571        final PackageStats stats = new PackageStats(null, -1);
24572        synchronized (mInstaller) {
24573            for (int userId : installedUserIds) {
24574                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24575                    freezer.close();
24576                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24577                            "Failed to measure package size");
24578                }
24579            }
24580        }
24581
24582        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24583                + stats.dataSize);
24584
24585        final long startFreeBytes = measurePath.getUsableSpace();
24586        final long sizeBytes;
24587        if (moveCompleteApp) {
24588            sizeBytes = stats.codeSize + stats.dataSize;
24589        } else {
24590            sizeBytes = stats.codeSize;
24591        }
24592
24593        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24594            freezer.close();
24595            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24596                    "Not enough free space to move");
24597        }
24598
24599        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24600
24601        final CountDownLatch installedLatch = new CountDownLatch(1);
24602        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24603            @Override
24604            public void onUserActionRequired(Intent intent) throws RemoteException {
24605                throw new IllegalStateException();
24606            }
24607
24608            @Override
24609            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24610                    Bundle extras) throws RemoteException {
24611                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24612                        + PackageManager.installStatusToString(returnCode, msg));
24613
24614                installedLatch.countDown();
24615                freezer.close();
24616
24617                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24618                switch (status) {
24619                    case PackageInstaller.STATUS_SUCCESS:
24620                        mMoveCallbacks.notifyStatusChanged(moveId,
24621                                PackageManager.MOVE_SUCCEEDED);
24622                        break;
24623                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24624                        mMoveCallbacks.notifyStatusChanged(moveId,
24625                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24626                        break;
24627                    default:
24628                        mMoveCallbacks.notifyStatusChanged(moveId,
24629                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24630                        break;
24631                }
24632            }
24633        };
24634
24635        final MoveInfo move;
24636        if (moveCompleteApp) {
24637            // Kick off a thread to report progress estimates
24638            new Thread() {
24639                @Override
24640                public void run() {
24641                    while (true) {
24642                        try {
24643                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24644                                break;
24645                            }
24646                        } catch (InterruptedException ignored) {
24647                        }
24648
24649                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24650                        final int progress = 10 + (int) MathUtils.constrain(
24651                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24652                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24653                    }
24654                }
24655            }.start();
24656
24657            final String dataAppName = codeFile.getName();
24658            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24659                    dataAppName, appId, seinfo, targetSdkVersion);
24660        } else {
24661            move = null;
24662        }
24663
24664        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24665
24666        final Message msg = mHandler.obtainMessage(INIT_COPY);
24667        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24668        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24669                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24670                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24671                PackageManager.INSTALL_REASON_UNKNOWN);
24672        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24673        msg.obj = params;
24674
24675        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24676                System.identityHashCode(msg.obj));
24677        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24678                System.identityHashCode(msg.obj));
24679
24680        mHandler.sendMessage(msg);
24681    }
24682
24683    @Override
24684    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24685        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24686
24687        final int realMoveId = mNextMoveId.getAndIncrement();
24688        final Bundle extras = new Bundle();
24689        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24690        mMoveCallbacks.notifyCreated(realMoveId, extras);
24691
24692        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24693            @Override
24694            public void onCreated(int moveId, Bundle extras) {
24695                // Ignored
24696            }
24697
24698            @Override
24699            public void onStatusChanged(int moveId, int status, long estMillis) {
24700                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24701            }
24702        };
24703
24704        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24705        storage.setPrimaryStorageUuid(volumeUuid, callback);
24706        return realMoveId;
24707    }
24708
24709    @Override
24710    public int getMoveStatus(int moveId) {
24711        mContext.enforceCallingOrSelfPermission(
24712                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24713        return mMoveCallbacks.mLastStatus.get(moveId);
24714    }
24715
24716    @Override
24717    public void registerMoveCallback(IPackageMoveObserver callback) {
24718        mContext.enforceCallingOrSelfPermission(
24719                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24720        mMoveCallbacks.register(callback);
24721    }
24722
24723    @Override
24724    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24725        mContext.enforceCallingOrSelfPermission(
24726                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24727        mMoveCallbacks.unregister(callback);
24728    }
24729
24730    @Override
24731    public boolean setInstallLocation(int loc) {
24732        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24733                null);
24734        if (getInstallLocation() == loc) {
24735            return true;
24736        }
24737        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24738                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24739            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24740                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24741            return true;
24742        }
24743        return false;
24744   }
24745
24746    @Override
24747    public int getInstallLocation() {
24748        // allow instant app access
24749        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24750                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24751                PackageHelper.APP_INSTALL_AUTO);
24752    }
24753
24754    /** Called by UserManagerService */
24755    void cleanUpUser(UserManagerService userManager, int userHandle) {
24756        synchronized (mPackages) {
24757            mDirtyUsers.remove(userHandle);
24758            mUserNeedsBadging.delete(userHandle);
24759            mSettings.removeUserLPw(userHandle);
24760            mPendingBroadcasts.remove(userHandle);
24761            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24762            removeUnusedPackagesLPw(userManager, userHandle);
24763        }
24764    }
24765
24766    /**
24767     * We're removing userHandle and would like to remove any downloaded packages
24768     * that are no longer in use by any other user.
24769     * @param userHandle the user being removed
24770     */
24771    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24772        final boolean DEBUG_CLEAN_APKS = false;
24773        int [] users = userManager.getUserIds();
24774        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24775        while (psit.hasNext()) {
24776            PackageSetting ps = psit.next();
24777            if (ps.pkg == null) {
24778                continue;
24779            }
24780            final String packageName = ps.pkg.packageName;
24781            // Skip over if system app
24782            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24783                continue;
24784            }
24785            if (DEBUG_CLEAN_APKS) {
24786                Slog.i(TAG, "Checking package " + packageName);
24787            }
24788            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24789            if (keep) {
24790                if (DEBUG_CLEAN_APKS) {
24791                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24792                }
24793            } else {
24794                for (int i = 0; i < users.length; i++) {
24795                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24796                        keep = true;
24797                        if (DEBUG_CLEAN_APKS) {
24798                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24799                                    + users[i]);
24800                        }
24801                        break;
24802                    }
24803                }
24804            }
24805            if (!keep) {
24806                if (DEBUG_CLEAN_APKS) {
24807                    Slog.i(TAG, "  Removing package " + packageName);
24808                }
24809                mHandler.post(new Runnable() {
24810                    public void run() {
24811                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24812                                userHandle, 0);
24813                    } //end run
24814                });
24815            }
24816        }
24817    }
24818
24819    /** Called by UserManagerService */
24820    void createNewUser(int userId, String[] disallowedPackages) {
24821        synchronized (mInstallLock) {
24822            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24823        }
24824        synchronized (mPackages) {
24825            scheduleWritePackageRestrictionsLocked(userId);
24826            scheduleWritePackageListLocked(userId);
24827            applyFactoryDefaultBrowserLPw(userId);
24828            primeDomainVerificationsLPw(userId);
24829        }
24830    }
24831
24832    void onNewUserCreated(final int userId) {
24833        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24834        // If permission review for legacy apps is required, we represent
24835        // dagerous permissions for such apps as always granted runtime
24836        // permissions to keep per user flag state whether review is needed.
24837        // Hence, if a new user is added we have to propagate dangerous
24838        // permission grants for these legacy apps.
24839        if (mPermissionReviewRequired) {
24840            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24841                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24842        }
24843    }
24844
24845    @Override
24846    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24847        mContext.enforceCallingOrSelfPermission(
24848                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24849                "Only package verification agents can read the verifier device identity");
24850
24851        synchronized (mPackages) {
24852            return mSettings.getVerifierDeviceIdentityLPw();
24853        }
24854    }
24855
24856    @Override
24857    public void setPermissionEnforced(String permission, boolean enforced) {
24858        // TODO: Now that we no longer change GID for storage, this should to away.
24859        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24860                "setPermissionEnforced");
24861        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24862            synchronized (mPackages) {
24863                if (mSettings.mReadExternalStorageEnforced == null
24864                        || mSettings.mReadExternalStorageEnforced != enforced) {
24865                    mSettings.mReadExternalStorageEnforced = enforced;
24866                    mSettings.writeLPr();
24867                }
24868            }
24869            // kill any non-foreground processes so we restart them and
24870            // grant/revoke the GID.
24871            final IActivityManager am = ActivityManager.getService();
24872            if (am != null) {
24873                final long token = Binder.clearCallingIdentity();
24874                try {
24875                    am.killProcessesBelowForeground("setPermissionEnforcement");
24876                } catch (RemoteException e) {
24877                } finally {
24878                    Binder.restoreCallingIdentity(token);
24879                }
24880            }
24881        } else {
24882            throw new IllegalArgumentException("No selective enforcement for " + permission);
24883        }
24884    }
24885
24886    @Override
24887    @Deprecated
24888    public boolean isPermissionEnforced(String permission) {
24889        // allow instant applications
24890        return true;
24891    }
24892
24893    @Override
24894    public boolean isStorageLow() {
24895        // allow instant applications
24896        final long token = Binder.clearCallingIdentity();
24897        try {
24898            final DeviceStorageMonitorInternal
24899                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24900            if (dsm != null) {
24901                return dsm.isMemoryLow();
24902            } else {
24903                return false;
24904            }
24905        } finally {
24906            Binder.restoreCallingIdentity(token);
24907        }
24908    }
24909
24910    @Override
24911    public IPackageInstaller getPackageInstaller() {
24912        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24913            return null;
24914        }
24915        return mInstallerService;
24916    }
24917
24918    @Override
24919    public IArtManager getArtManager() {
24920        return mArtManagerService;
24921    }
24922
24923    private boolean userNeedsBadging(int userId) {
24924        int index = mUserNeedsBadging.indexOfKey(userId);
24925        if (index < 0) {
24926            final UserInfo userInfo;
24927            final long token = Binder.clearCallingIdentity();
24928            try {
24929                userInfo = sUserManager.getUserInfo(userId);
24930            } finally {
24931                Binder.restoreCallingIdentity(token);
24932            }
24933            final boolean b;
24934            if (userInfo != null && userInfo.isManagedProfile()) {
24935                b = true;
24936            } else {
24937                b = false;
24938            }
24939            mUserNeedsBadging.put(userId, b);
24940            return b;
24941        }
24942        return mUserNeedsBadging.valueAt(index);
24943    }
24944
24945    @Override
24946    public KeySet getKeySetByAlias(String packageName, String alias) {
24947        if (packageName == null || alias == null) {
24948            return null;
24949        }
24950        synchronized(mPackages) {
24951            final PackageParser.Package pkg = mPackages.get(packageName);
24952            if (pkg == null) {
24953                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24954                throw new IllegalArgumentException("Unknown package: " + packageName);
24955            }
24956            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24957            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24958                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24959                throw new IllegalArgumentException("Unknown package: " + packageName);
24960            }
24961            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24962            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24963        }
24964    }
24965
24966    @Override
24967    public KeySet getSigningKeySet(String packageName) {
24968        if (packageName == null) {
24969            return null;
24970        }
24971        synchronized(mPackages) {
24972            final int callingUid = Binder.getCallingUid();
24973            final int callingUserId = UserHandle.getUserId(callingUid);
24974            final PackageParser.Package pkg = mPackages.get(packageName);
24975            if (pkg == null) {
24976                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24977                throw new IllegalArgumentException("Unknown package: " + packageName);
24978            }
24979            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24980            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24981                // filter and pretend the package doesn't exist
24982                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24983                        + ", uid:" + callingUid);
24984                throw new IllegalArgumentException("Unknown package: " + packageName);
24985            }
24986            if (pkg.applicationInfo.uid != callingUid
24987                    && Process.SYSTEM_UID != callingUid) {
24988                throw new SecurityException("May not access signing KeySet of other apps.");
24989            }
24990            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24991            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24992        }
24993    }
24994
24995    @Override
24996    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24997        final int callingUid = Binder.getCallingUid();
24998        if (getInstantAppPackageName(callingUid) != null) {
24999            return false;
25000        }
25001        if (packageName == null || ks == null) {
25002            return false;
25003        }
25004        synchronized(mPackages) {
25005            final PackageParser.Package pkg = mPackages.get(packageName);
25006            if (pkg == null
25007                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
25008                            UserHandle.getUserId(callingUid))) {
25009                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
25010                throw new IllegalArgumentException("Unknown package: " + packageName);
25011            }
25012            IBinder ksh = ks.getToken();
25013            if (ksh instanceof KeySetHandle) {
25014                KeySetManagerService ksms = mSettings.mKeySetManagerService;
25015                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
25016            }
25017            return false;
25018        }
25019    }
25020
25021    @Override
25022    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
25023        final int callingUid = Binder.getCallingUid();
25024        if (getInstantAppPackageName(callingUid) != null) {
25025            return false;
25026        }
25027        if (packageName == null || ks == null) {
25028            return false;
25029        }
25030        synchronized(mPackages) {
25031            final PackageParser.Package pkg = mPackages.get(packageName);
25032            if (pkg == null
25033                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
25034                            UserHandle.getUserId(callingUid))) {
25035                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
25036                throw new IllegalArgumentException("Unknown package: " + packageName);
25037            }
25038            IBinder ksh = ks.getToken();
25039            if (ksh instanceof KeySetHandle) {
25040                KeySetManagerService ksms = mSettings.mKeySetManagerService;
25041                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
25042            }
25043            return false;
25044        }
25045    }
25046
25047    private void deletePackageIfUnusedLPr(final String packageName) {
25048        PackageSetting ps = mSettings.mPackages.get(packageName);
25049        if (ps == null) {
25050            return;
25051        }
25052        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
25053            // TODO Implement atomic delete if package is unused
25054            // It is currently possible that the package will be deleted even if it is installed
25055            // after this method returns.
25056            mHandler.post(new Runnable() {
25057                public void run() {
25058                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
25059                            0, PackageManager.DELETE_ALL_USERS);
25060                }
25061            });
25062        }
25063    }
25064
25065    /**
25066     * Check and throw if the given before/after packages would be considered a
25067     * downgrade.
25068     */
25069    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
25070            throws PackageManagerException {
25071        if (after.versionCode < before.mVersionCode) {
25072            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25073                    "Update version code " + after.versionCode + " is older than current "
25074                    + before.mVersionCode);
25075        } else if (after.versionCode == before.mVersionCode) {
25076            if (after.baseRevisionCode < before.baseRevisionCode) {
25077                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25078                        "Update base revision code " + after.baseRevisionCode
25079                        + " is older than current " + before.baseRevisionCode);
25080            }
25081
25082            if (!ArrayUtils.isEmpty(after.splitNames)) {
25083                for (int i = 0; i < after.splitNames.length; i++) {
25084                    final String splitName = after.splitNames[i];
25085                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
25086                    if (j != -1) {
25087                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
25088                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25089                                    "Update split " + splitName + " revision code "
25090                                    + after.splitRevisionCodes[i] + " is older than current "
25091                                    + before.splitRevisionCodes[j]);
25092                        }
25093                    }
25094                }
25095            }
25096        }
25097    }
25098
25099    private static class MoveCallbacks extends Handler {
25100        private static final int MSG_CREATED = 1;
25101        private static final int MSG_STATUS_CHANGED = 2;
25102
25103        private final RemoteCallbackList<IPackageMoveObserver>
25104                mCallbacks = new RemoteCallbackList<>();
25105
25106        private final SparseIntArray mLastStatus = new SparseIntArray();
25107
25108        public MoveCallbacks(Looper looper) {
25109            super(looper);
25110        }
25111
25112        public void register(IPackageMoveObserver callback) {
25113            mCallbacks.register(callback);
25114        }
25115
25116        public void unregister(IPackageMoveObserver callback) {
25117            mCallbacks.unregister(callback);
25118        }
25119
25120        @Override
25121        public void handleMessage(Message msg) {
25122            final SomeArgs args = (SomeArgs) msg.obj;
25123            final int n = mCallbacks.beginBroadcast();
25124            for (int i = 0; i < n; i++) {
25125                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
25126                try {
25127                    invokeCallback(callback, msg.what, args);
25128                } catch (RemoteException ignored) {
25129                }
25130            }
25131            mCallbacks.finishBroadcast();
25132            args.recycle();
25133        }
25134
25135        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
25136                throws RemoteException {
25137            switch (what) {
25138                case MSG_CREATED: {
25139                    callback.onCreated(args.argi1, (Bundle) args.arg2);
25140                    break;
25141                }
25142                case MSG_STATUS_CHANGED: {
25143                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
25144                    break;
25145                }
25146            }
25147        }
25148
25149        private void notifyCreated(int moveId, Bundle extras) {
25150            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
25151
25152            final SomeArgs args = SomeArgs.obtain();
25153            args.argi1 = moveId;
25154            args.arg2 = extras;
25155            obtainMessage(MSG_CREATED, args).sendToTarget();
25156        }
25157
25158        private void notifyStatusChanged(int moveId, int status) {
25159            notifyStatusChanged(moveId, status, -1);
25160        }
25161
25162        private void notifyStatusChanged(int moveId, int status, long estMillis) {
25163            Slog.v(TAG, "Move " + moveId + " status " + status);
25164
25165            final SomeArgs args = SomeArgs.obtain();
25166            args.argi1 = moveId;
25167            args.argi2 = status;
25168            args.arg3 = estMillis;
25169            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
25170
25171            synchronized (mLastStatus) {
25172                mLastStatus.put(moveId, status);
25173            }
25174        }
25175    }
25176
25177    private final static class OnPermissionChangeListeners extends Handler {
25178        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
25179
25180        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
25181                new RemoteCallbackList<>();
25182
25183        public OnPermissionChangeListeners(Looper looper) {
25184            super(looper);
25185        }
25186
25187        @Override
25188        public void handleMessage(Message msg) {
25189            switch (msg.what) {
25190                case MSG_ON_PERMISSIONS_CHANGED: {
25191                    final int uid = msg.arg1;
25192                    handleOnPermissionsChanged(uid);
25193                } break;
25194            }
25195        }
25196
25197        public void addListenerLocked(IOnPermissionsChangeListener listener) {
25198            mPermissionListeners.register(listener);
25199
25200        }
25201
25202        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
25203            mPermissionListeners.unregister(listener);
25204        }
25205
25206        public void onPermissionsChanged(int uid) {
25207            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
25208                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
25209            }
25210        }
25211
25212        private void handleOnPermissionsChanged(int uid) {
25213            final int count = mPermissionListeners.beginBroadcast();
25214            try {
25215                for (int i = 0; i < count; i++) {
25216                    IOnPermissionsChangeListener callback = mPermissionListeners
25217                            .getBroadcastItem(i);
25218                    try {
25219                        callback.onPermissionsChanged(uid);
25220                    } catch (RemoteException e) {
25221                        Log.e(TAG, "Permission listener is dead", e);
25222                    }
25223                }
25224            } finally {
25225                mPermissionListeners.finishBroadcast();
25226            }
25227        }
25228    }
25229
25230    private class PackageManagerNative extends IPackageManagerNative.Stub {
25231        @Override
25232        public String[] getNamesForUids(int[] uids) throws RemoteException {
25233            final String[] results = PackageManagerService.this.getNamesForUids(uids);
25234            // massage results so they can be parsed by the native binder
25235            for (int i = results.length - 1; i >= 0; --i) {
25236                if (results[i] == null) {
25237                    results[i] = "";
25238                }
25239            }
25240            return results;
25241        }
25242
25243        // NB: this differentiates between preloads and sideloads
25244        @Override
25245        public String getInstallerForPackage(String packageName) throws RemoteException {
25246            final String installerName = getInstallerPackageName(packageName);
25247            if (!TextUtils.isEmpty(installerName)) {
25248                return installerName;
25249            }
25250            // differentiate between preload and sideload
25251            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25252            ApplicationInfo appInfo = getApplicationInfo(packageName,
25253                                    /*flags*/ 0,
25254                                    /*userId*/ callingUser);
25255            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
25256                return "preload";
25257            }
25258            return "";
25259        }
25260
25261        @Override
25262        public int getVersionCodeForPackage(String packageName) throws RemoteException {
25263            try {
25264                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25265                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
25266                if (pInfo != null) {
25267                    return pInfo.versionCode;
25268                }
25269            } catch (Exception e) {
25270            }
25271            return 0;
25272        }
25273    }
25274
25275    private class PackageManagerInternalImpl extends PackageManagerInternal {
25276        @Override
25277        public void setLocationPackagesProvider(PackagesProvider provider) {
25278            synchronized (mPackages) {
25279                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
25280            }
25281        }
25282
25283        @Override
25284        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25285            synchronized (mPackages) {
25286                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
25287            }
25288        }
25289
25290        @Override
25291        public void setSmsAppPackagesProvider(PackagesProvider provider) {
25292            synchronized (mPackages) {
25293                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
25294            }
25295        }
25296
25297        @Override
25298        public void setDialerAppPackagesProvider(PackagesProvider provider) {
25299            synchronized (mPackages) {
25300                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
25301            }
25302        }
25303
25304        @Override
25305        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25306            synchronized (mPackages) {
25307                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
25308            }
25309        }
25310
25311        @Override
25312        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25313            synchronized (mPackages) {
25314                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25315            }
25316        }
25317
25318        @Override
25319        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25320            synchronized (mPackages) {
25321                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25322                        packageName, userId);
25323            }
25324        }
25325
25326        @Override
25327        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25328            synchronized (mPackages) {
25329                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25330                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25331                        packageName, userId);
25332            }
25333        }
25334
25335        @Override
25336        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25337            synchronized (mPackages) {
25338                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25339                        packageName, userId);
25340            }
25341        }
25342
25343        @Override
25344        public void setKeepUninstalledPackages(final List<String> packageList) {
25345            Preconditions.checkNotNull(packageList);
25346            List<String> removedFromList = null;
25347            synchronized (mPackages) {
25348                if (mKeepUninstalledPackages != null) {
25349                    final int packagesCount = mKeepUninstalledPackages.size();
25350                    for (int i = 0; i < packagesCount; i++) {
25351                        String oldPackage = mKeepUninstalledPackages.get(i);
25352                        if (packageList != null && packageList.contains(oldPackage)) {
25353                            continue;
25354                        }
25355                        if (removedFromList == null) {
25356                            removedFromList = new ArrayList<>();
25357                        }
25358                        removedFromList.add(oldPackage);
25359                    }
25360                }
25361                mKeepUninstalledPackages = new ArrayList<>(packageList);
25362                if (removedFromList != null) {
25363                    final int removedCount = removedFromList.size();
25364                    for (int i = 0; i < removedCount; i++) {
25365                        deletePackageIfUnusedLPr(removedFromList.get(i));
25366                    }
25367                }
25368            }
25369        }
25370
25371        @Override
25372        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25373            synchronized (mPackages) {
25374                // If we do not support permission review, done.
25375                if (!mPermissionReviewRequired) {
25376                    return false;
25377                }
25378
25379                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25380                if (packageSetting == null) {
25381                    return false;
25382                }
25383
25384                // Permission review applies only to apps not supporting the new permission model.
25385                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25386                    return false;
25387                }
25388
25389                // Legacy apps have the permission and get user consent on launch.
25390                PermissionsState permissionsState = packageSetting.getPermissionsState();
25391                return permissionsState.isPermissionReviewRequired(userId);
25392            }
25393        }
25394
25395        @Override
25396        public PackageInfo getPackageInfo(
25397                String packageName, int flags, int filterCallingUid, int userId) {
25398            return PackageManagerService.this
25399                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25400                            flags, filterCallingUid, userId);
25401        }
25402
25403        @Override
25404        public ApplicationInfo getApplicationInfo(
25405                String packageName, int flags, int filterCallingUid, int userId) {
25406            return PackageManagerService.this
25407                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25408        }
25409
25410        @Override
25411        public ActivityInfo getActivityInfo(
25412                ComponentName component, int flags, int filterCallingUid, int userId) {
25413            return PackageManagerService.this
25414                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25415        }
25416
25417        @Override
25418        public List<ResolveInfo> queryIntentActivities(
25419                Intent intent, int flags, int filterCallingUid, int userId) {
25420            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25421            return PackageManagerService.this
25422                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25423                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25424        }
25425
25426        @Override
25427        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25428                int userId) {
25429            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25430        }
25431
25432        @Override
25433        public void setDeviceAndProfileOwnerPackages(
25434                int deviceOwnerUserId, String deviceOwnerPackage,
25435                SparseArray<String> profileOwnerPackages) {
25436            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25437                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25438        }
25439
25440        @Override
25441        public boolean isPackageDataProtected(int userId, String packageName) {
25442            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25443        }
25444
25445        @Override
25446        public boolean isPackageEphemeral(int userId, String packageName) {
25447            synchronized (mPackages) {
25448                final PackageSetting ps = mSettings.mPackages.get(packageName);
25449                return ps != null ? ps.getInstantApp(userId) : false;
25450            }
25451        }
25452
25453        @Override
25454        public boolean wasPackageEverLaunched(String packageName, int userId) {
25455            synchronized (mPackages) {
25456                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25457            }
25458        }
25459
25460        @Override
25461        public void grantRuntimePermission(String packageName, String name, int userId,
25462                boolean overridePolicy) {
25463            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25464                    overridePolicy);
25465        }
25466
25467        @Override
25468        public void revokeRuntimePermission(String packageName, String name, int userId,
25469                boolean overridePolicy) {
25470            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25471                    overridePolicy);
25472        }
25473
25474        @Override
25475        public String getNameForUid(int uid) {
25476            return PackageManagerService.this.getNameForUid(uid);
25477        }
25478
25479        @Override
25480        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25481                Intent origIntent, String resolvedType, String callingPackage,
25482                Bundle verificationBundle, int userId) {
25483            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25484                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25485                    userId);
25486        }
25487
25488        @Override
25489        public void grantEphemeralAccess(int userId, Intent intent,
25490                int targetAppId, int ephemeralAppId) {
25491            synchronized (mPackages) {
25492                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25493                        targetAppId, ephemeralAppId);
25494            }
25495        }
25496
25497        @Override
25498        public boolean isInstantAppInstallerComponent(ComponentName component) {
25499            synchronized (mPackages) {
25500                return mInstantAppInstallerActivity != null
25501                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25502            }
25503        }
25504
25505        @Override
25506        public void pruneInstantApps() {
25507            mInstantAppRegistry.pruneInstantApps();
25508        }
25509
25510        @Override
25511        public String getSetupWizardPackageName() {
25512            return mSetupWizardPackage;
25513        }
25514
25515        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25516            if (policy != null) {
25517                mExternalSourcesPolicy = policy;
25518            }
25519        }
25520
25521        @Override
25522        public boolean isPackagePersistent(String packageName) {
25523            synchronized (mPackages) {
25524                PackageParser.Package pkg = mPackages.get(packageName);
25525                return pkg != null
25526                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25527                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25528                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25529                        : false;
25530            }
25531        }
25532
25533        @Override
25534        public List<PackageInfo> getOverlayPackages(int userId) {
25535            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25536            synchronized (mPackages) {
25537                for (PackageParser.Package p : mPackages.values()) {
25538                    if (p.mOverlayTarget != null) {
25539                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25540                        if (pkg != null) {
25541                            overlayPackages.add(pkg);
25542                        }
25543                    }
25544                }
25545            }
25546            return overlayPackages;
25547        }
25548
25549        @Override
25550        public List<String> getTargetPackageNames(int userId) {
25551            List<String> targetPackages = new ArrayList<>();
25552            synchronized (mPackages) {
25553                for (PackageParser.Package p : mPackages.values()) {
25554                    if (p.mOverlayTarget == null) {
25555                        targetPackages.add(p.packageName);
25556                    }
25557                }
25558            }
25559            return targetPackages;
25560        }
25561
25562        @Override
25563        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25564                @Nullable List<String> overlayPackageNames) {
25565            synchronized (mPackages) {
25566                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25567                    Slog.e(TAG, "failed to find package " + targetPackageName);
25568                    return false;
25569                }
25570                ArrayList<String> overlayPaths = null;
25571                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25572                    final int N = overlayPackageNames.size();
25573                    overlayPaths = new ArrayList<>(N);
25574                    for (int i = 0; i < N; i++) {
25575                        final String packageName = overlayPackageNames.get(i);
25576                        final PackageParser.Package pkg = mPackages.get(packageName);
25577                        if (pkg == null) {
25578                            Slog.e(TAG, "failed to find package " + packageName);
25579                            return false;
25580                        }
25581                        overlayPaths.add(pkg.baseCodePath);
25582                    }
25583                }
25584
25585                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25586                ps.setOverlayPaths(overlayPaths, userId);
25587                return true;
25588            }
25589        }
25590
25591        @Override
25592        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25593                int flags, int userId) {
25594            return resolveIntentInternal(
25595                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25596        }
25597
25598        @Override
25599        public ResolveInfo resolveService(Intent intent, String resolvedType,
25600                int flags, int userId, int callingUid) {
25601            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25602        }
25603
25604        @Override
25605        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25606            synchronized (mPackages) {
25607                mIsolatedOwners.put(isolatedUid, ownerUid);
25608            }
25609        }
25610
25611        @Override
25612        public void removeIsolatedUid(int isolatedUid) {
25613            synchronized (mPackages) {
25614                mIsolatedOwners.delete(isolatedUid);
25615            }
25616        }
25617
25618        @Override
25619        public int getUidTargetSdkVersion(int uid) {
25620            synchronized (mPackages) {
25621                return getUidTargetSdkVersionLockedLPr(uid);
25622            }
25623        }
25624
25625        @Override
25626        public boolean canAccessInstantApps(int callingUid, int userId) {
25627            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25628        }
25629
25630        @Override
25631        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
25632            synchronized (mPackages) {
25633                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
25634            }
25635        }
25636
25637        @Override
25638        public void notifyPackageUse(String packageName, int reason) {
25639            synchronized (mPackages) {
25640                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
25641            }
25642        }
25643    }
25644
25645    @Override
25646    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25647        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25648        synchronized (mPackages) {
25649            final long identity = Binder.clearCallingIdentity();
25650            try {
25651                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25652                        packageNames, userId);
25653            } finally {
25654                Binder.restoreCallingIdentity(identity);
25655            }
25656        }
25657    }
25658
25659    @Override
25660    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25661        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25662        synchronized (mPackages) {
25663            final long identity = Binder.clearCallingIdentity();
25664            try {
25665                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25666                        packageNames, userId);
25667            } finally {
25668                Binder.restoreCallingIdentity(identity);
25669            }
25670        }
25671    }
25672
25673    private static void enforceSystemOrPhoneCaller(String tag) {
25674        int callingUid = Binder.getCallingUid();
25675        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25676            throw new SecurityException(
25677                    "Cannot call " + tag + " from UID " + callingUid);
25678        }
25679    }
25680
25681    boolean isHistoricalPackageUsageAvailable() {
25682        return mPackageUsage.isHistoricalPackageUsageAvailable();
25683    }
25684
25685    /**
25686     * Return a <b>copy</b> of the collection of packages known to the package manager.
25687     * @return A copy of the values of mPackages.
25688     */
25689    Collection<PackageParser.Package> getPackages() {
25690        synchronized (mPackages) {
25691            return new ArrayList<>(mPackages.values());
25692        }
25693    }
25694
25695    /**
25696     * Logs process start information (including base APK hash) to the security log.
25697     * @hide
25698     */
25699    @Override
25700    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25701            String apkFile, int pid) {
25702        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25703            return;
25704        }
25705        if (!SecurityLog.isLoggingEnabled()) {
25706            return;
25707        }
25708        Bundle data = new Bundle();
25709        data.putLong("startTimestamp", System.currentTimeMillis());
25710        data.putString("processName", processName);
25711        data.putInt("uid", uid);
25712        data.putString("seinfo", seinfo);
25713        data.putString("apkFile", apkFile);
25714        data.putInt("pid", pid);
25715        Message msg = mProcessLoggingHandler.obtainMessage(
25716                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25717        msg.setData(data);
25718        mProcessLoggingHandler.sendMessage(msg);
25719    }
25720
25721    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25722        return mCompilerStats.getPackageStats(pkgName);
25723    }
25724
25725    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25726        return getOrCreateCompilerPackageStats(pkg.packageName);
25727    }
25728
25729    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25730        return mCompilerStats.getOrCreatePackageStats(pkgName);
25731    }
25732
25733    public void deleteCompilerPackageStats(String pkgName) {
25734        mCompilerStats.deletePackageStats(pkgName);
25735    }
25736
25737    @Override
25738    public int getInstallReason(String packageName, int userId) {
25739        final int callingUid = Binder.getCallingUid();
25740        enforceCrossUserPermission(callingUid, userId,
25741                true /* requireFullPermission */, false /* checkShell */,
25742                "get install reason");
25743        synchronized (mPackages) {
25744            final PackageSetting ps = mSettings.mPackages.get(packageName);
25745            if (filterAppAccessLPr(ps, callingUid, userId)) {
25746                return PackageManager.INSTALL_REASON_UNKNOWN;
25747            }
25748            if (ps != null) {
25749                return ps.getInstallReason(userId);
25750            }
25751        }
25752        return PackageManager.INSTALL_REASON_UNKNOWN;
25753    }
25754
25755    @Override
25756    public boolean canRequestPackageInstalls(String packageName, int userId) {
25757        return canRequestPackageInstallsInternal(packageName, 0, userId,
25758                true /* throwIfPermNotDeclared*/);
25759    }
25760
25761    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25762            boolean throwIfPermNotDeclared) {
25763        int callingUid = Binder.getCallingUid();
25764        int uid = getPackageUid(packageName, 0, userId);
25765        if (callingUid != uid && callingUid != Process.ROOT_UID
25766                && callingUid != Process.SYSTEM_UID) {
25767            throw new SecurityException(
25768                    "Caller uid " + callingUid + " does not own package " + packageName);
25769        }
25770        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25771        if (info == null) {
25772            return false;
25773        }
25774        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25775            return false;
25776        }
25777        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25778        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25779        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25780            if (throwIfPermNotDeclared) {
25781                throw new SecurityException("Need to declare " + appOpPermission
25782                        + " to call this api");
25783            } else {
25784                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25785                return false;
25786            }
25787        }
25788        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25789            return false;
25790        }
25791        if (mExternalSourcesPolicy != null) {
25792            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25793            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25794                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25795            }
25796        }
25797        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25798    }
25799
25800    @Override
25801    public ComponentName getInstantAppResolverSettingsComponent() {
25802        return mInstantAppResolverSettingsComponent;
25803    }
25804
25805    @Override
25806    public ComponentName getInstantAppInstallerComponent() {
25807        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25808            return null;
25809        }
25810        return mInstantAppInstallerActivity == null
25811                ? null : mInstantAppInstallerActivity.getComponentName();
25812    }
25813
25814    @Override
25815    public String getInstantAppAndroidId(String packageName, int userId) {
25816        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25817                "getInstantAppAndroidId");
25818        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25819                true /* requireFullPermission */, false /* checkShell */,
25820                "getInstantAppAndroidId");
25821        // Make sure the target is an Instant App.
25822        if (!isInstantApp(packageName, userId)) {
25823            return null;
25824        }
25825        synchronized (mPackages) {
25826            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25827        }
25828    }
25829
25830    boolean canHaveOatDir(String packageName) {
25831        synchronized (mPackages) {
25832            PackageParser.Package p = mPackages.get(packageName);
25833            if (p == null) {
25834                return false;
25835            }
25836            return p.canHaveOatDir();
25837        }
25838    }
25839
25840    private String getOatDir(PackageParser.Package pkg) {
25841        if (!pkg.canHaveOatDir()) {
25842            return null;
25843        }
25844        File codePath = new File(pkg.codePath);
25845        if (codePath.isDirectory()) {
25846            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25847        }
25848        return null;
25849    }
25850
25851    void deleteOatArtifactsOfPackage(String packageName) {
25852        final String[] instructionSets;
25853        final List<String> codePaths;
25854        final String oatDir;
25855        final PackageParser.Package pkg;
25856        synchronized (mPackages) {
25857            pkg = mPackages.get(packageName);
25858        }
25859        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25860        codePaths = pkg.getAllCodePaths();
25861        oatDir = getOatDir(pkg);
25862
25863        for (String codePath : codePaths) {
25864            for (String isa : instructionSets) {
25865                try {
25866                    mInstaller.deleteOdex(codePath, isa, oatDir);
25867                } catch (InstallerException e) {
25868                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25869                }
25870            }
25871        }
25872    }
25873
25874    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25875        Set<String> unusedPackages = new HashSet<>();
25876        long currentTimeInMillis = System.currentTimeMillis();
25877        synchronized (mPackages) {
25878            for (PackageParser.Package pkg : mPackages.values()) {
25879                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25880                if (ps == null) {
25881                    continue;
25882                }
25883                PackageDexUsage.PackageUseInfo packageUseInfo =
25884                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25885                if (PackageManagerServiceUtils
25886                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25887                                downgradeTimeThresholdMillis, packageUseInfo,
25888                                pkg.getLatestPackageUseTimeInMills(),
25889                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25890                    unusedPackages.add(pkg.packageName);
25891                }
25892            }
25893        }
25894        return unusedPackages;
25895    }
25896}
25897
25898interface PackageSender {
25899    void sendPackageBroadcast(final String action, final String pkg,
25900        final Bundle extras, final int flags, final String targetPkg,
25901        final IIntentReceiver finishedReceiver, final int[] userIds);
25902    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25903        boolean includeStopped, int appId, int... userIds);
25904}
25905