PackageManagerService.java revision 29c772cb4835794e02084043be7ca139c1fb2171
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.ArtManager;
181import android.content.pm.dex.DexMetadataHelper;
182import android.content.pm.dex.IArtManager;
183import android.content.res.Resources;
184import android.database.ContentObserver;
185import android.graphics.Bitmap;
186import android.hardware.display.DisplayManager;
187import android.net.Uri;
188import android.os.Binder;
189import android.os.Build;
190import android.os.Bundle;
191import android.os.Debug;
192import android.os.Environment;
193import android.os.Environment.UserEnvironment;
194import android.os.FileUtils;
195import android.os.Handler;
196import android.os.IBinder;
197import android.os.Looper;
198import android.os.Message;
199import android.os.Parcel;
200import android.os.ParcelFileDescriptor;
201import android.os.PatternMatcher;
202import android.os.Process;
203import android.os.RemoteCallbackList;
204import android.os.RemoteException;
205import android.os.ResultReceiver;
206import android.os.SELinux;
207import android.os.ServiceManager;
208import android.os.ShellCallback;
209import android.os.SystemClock;
210import android.os.SystemProperties;
211import android.os.Trace;
212import android.os.UserHandle;
213import android.os.UserManager;
214import android.os.UserManagerInternal;
215import android.os.storage.IStorageManager;
216import android.os.storage.StorageEventListener;
217import android.os.storage.StorageManager;
218import android.os.storage.StorageManagerInternal;
219import android.os.storage.VolumeInfo;
220import android.os.storage.VolumeRecord;
221import android.provider.Settings.Global;
222import android.provider.Settings.Secure;
223import android.security.KeyStore;
224import android.security.SystemKeyStore;
225import android.service.pm.PackageServiceDumpProto;
226import android.system.ErrnoException;
227import android.system.Os;
228import android.text.TextUtils;
229import android.text.format.DateUtils;
230import android.util.ArrayMap;
231import android.util.ArraySet;
232import android.util.Base64;
233import android.util.TimingsTraceLog;
234import android.util.DisplayMetrics;
235import android.util.EventLog;
236import android.util.ExceptionUtils;
237import android.util.Log;
238import android.util.LogPrinter;
239import android.util.MathUtils;
240import android.util.PackageUtils;
241import android.util.Pair;
242import android.util.PrintStreamPrinter;
243import android.util.Slog;
244import android.util.SparseArray;
245import android.util.SparseBooleanArray;
246import android.util.SparseIntArray;
247import android.util.Xml;
248import android.util.jar.StrictJarFile;
249import android.util.proto.ProtoOutputStream;
250import android.view.Display;
251
252import com.android.internal.R;
253import com.android.internal.annotations.GuardedBy;
254import com.android.internal.app.IMediaContainerService;
255import com.android.internal.app.ResolverActivity;
256import com.android.internal.content.NativeLibraryHelper;
257import com.android.internal.content.PackageHelper;
258import com.android.internal.logging.MetricsLogger;
259import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
260import com.android.internal.os.IParcelFileDescriptorFactory;
261import com.android.internal.os.RoSystemProperties;
262import com.android.internal.os.SomeArgs;
263import com.android.internal.os.Zygote;
264import com.android.internal.telephony.CarrierAppUtils;
265import com.android.internal.util.ArrayUtils;
266import com.android.internal.util.ConcurrentUtils;
267import com.android.internal.util.DumpUtils;
268import com.android.internal.util.FastPrintWriter;
269import com.android.internal.util.FastXmlSerializer;
270import com.android.internal.util.IndentingPrintWriter;
271import com.android.internal.util.Preconditions;
272import com.android.internal.util.XmlUtils;
273import com.android.server.AttributeCache;
274import com.android.server.DeviceIdleController;
275import com.android.server.EventLogTags;
276import com.android.server.FgThread;
277import com.android.server.IntentResolver;
278import com.android.server.LocalServices;
279import com.android.server.LockGuard;
280import com.android.server.ServiceThread;
281import com.android.server.SystemConfig;
282import com.android.server.SystemServerInitThreadPool;
283import com.android.server.Watchdog;
284import com.android.server.net.NetworkPolicyManagerInternal;
285import com.android.server.pm.Installer.InstallerException;
286import com.android.server.pm.PermissionsState.PermissionState;
287import com.android.server.pm.Settings.DatabaseVersion;
288import com.android.server.pm.Settings.VersionInfo;
289import com.android.server.pm.dex.ArtManagerService;
290import com.android.server.pm.dex.DexLogger;
291import com.android.server.pm.dex.DexManager;
292import com.android.server.pm.dex.DexoptOptions;
293import com.android.server.pm.dex.PackageDexUsage;
294import com.android.server.storage.DeviceStorageMonitorInternal;
295
296import dalvik.system.CloseGuard;
297import dalvik.system.VMRuntime;
298
299import libcore.io.IoUtils;
300import libcore.io.Streams;
301import libcore.util.EmptyArray;
302
303import org.xmlpull.v1.XmlPullParser;
304import org.xmlpull.v1.XmlPullParserException;
305import org.xmlpull.v1.XmlSerializer;
306
307import java.io.BufferedOutputStream;
308import java.io.BufferedReader;
309import java.io.ByteArrayInputStream;
310import java.io.ByteArrayOutputStream;
311import java.io.File;
312import java.io.FileDescriptor;
313import java.io.FileInputStream;
314import java.io.FileOutputStream;
315import java.io.FileReader;
316import java.io.FilenameFilter;
317import java.io.IOException;
318import java.io.InputStream;
319import java.io.OutputStream;
320import java.io.PrintWriter;
321import java.lang.annotation.Retention;
322import java.lang.annotation.RetentionPolicy;
323import java.nio.charset.StandardCharsets;
324import java.security.DigestInputStream;
325import java.security.MessageDigest;
326import java.security.NoSuchAlgorithmException;
327import java.security.PublicKey;
328import java.security.SecureRandom;
329import java.security.cert.Certificate;
330import java.security.cert.CertificateEncodingException;
331import java.security.cert.CertificateException;
332import java.text.SimpleDateFormat;
333import java.util.ArrayList;
334import java.util.Arrays;
335import java.util.Collection;
336import java.util.Collections;
337import java.util.Comparator;
338import java.util.Date;
339import java.util.HashMap;
340import java.util.HashSet;
341import java.util.Iterator;
342import java.util.LinkedHashSet;
343import java.util.List;
344import java.util.Map;
345import java.util.Objects;
346import java.util.Set;
347import java.util.concurrent.CountDownLatch;
348import java.util.concurrent.Future;
349import java.util.concurrent.TimeUnit;
350import java.util.concurrent.atomic.AtomicBoolean;
351import java.util.concurrent.atomic.AtomicInteger;
352import java.util.zip.GZIPInputStream;
353
354/**
355 * Keep track of all those APKs everywhere.
356 * <p>
357 * Internally there are two important locks:
358 * <ul>
359 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
360 * and other related state. It is a fine-grained lock that should only be held
361 * momentarily, as it's one of the most contended locks in the system.
362 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
363 * operations typically involve heavy lifting of application data on disk. Since
364 * {@code installd} is single-threaded, and it's operations can often be slow,
365 * this lock should never be acquired while already holding {@link #mPackages}.
366 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
367 * holding {@link #mInstallLock}.
368 * </ul>
369 * Many internal methods rely on the caller to hold the appropriate locks, and
370 * this contract is expressed through method name suffixes:
371 * <ul>
372 * <li>fooLI(): the caller must hold {@link #mInstallLock}
373 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
374 * being modified must be frozen
375 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
376 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
377 * </ul>
378 * <p>
379 * Because this class is very central to the platform's security; please run all
380 * CTS and unit tests whenever making modifications:
381 *
382 * <pre>
383 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
384 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
385 * </pre>
386 */
387public class PackageManagerService extends IPackageManager.Stub
388        implements PackageSender {
389    static final String TAG = "PackageManager";
390    static final boolean DEBUG_SETTINGS = false;
391    static final boolean DEBUG_PREFERRED = false;
392    static final boolean DEBUG_UPGRADE = false;
393    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
394    private static final boolean DEBUG_BACKUP = false;
395    private static final boolean DEBUG_INSTALL = false;
396    private static final boolean DEBUG_REMOVE = false;
397    private static final boolean DEBUG_BROADCASTS = false;
398    private static final boolean DEBUG_SHOW_INFO = false;
399    private static final boolean DEBUG_PACKAGE_INFO = false;
400    private static final boolean DEBUG_INTENT_MATCHING = false;
401    private static final boolean DEBUG_PACKAGE_SCANNING = false;
402    private static final boolean DEBUG_VERIFY = false;
403    private static final boolean DEBUG_FILTERS = false;
404    private static final boolean DEBUG_PERMISSIONS = false;
405    private static final boolean DEBUG_SHARED_LIBRARIES = false;
406    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
407
408    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
409    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
410    // user, but by default initialize to this.
411    public static final boolean DEBUG_DEXOPT = false;
412
413    private static final boolean DEBUG_ABI_SELECTION = false;
414    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
415    private static final boolean DEBUG_TRIAGED_MISSING = false;
416    private static final boolean DEBUG_APP_DATA = false;
417
418    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
419    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
420
421    private static final boolean HIDE_EPHEMERAL_APIS = false;
422
423    private static final boolean ENABLE_FREE_CACHE_V2 =
424            SystemProperties.getBoolean("fw.free_cache_v2", true);
425
426    private static final int RADIO_UID = Process.PHONE_UID;
427    private static final int LOG_UID = Process.LOG_UID;
428    private static final int NFC_UID = Process.NFC_UID;
429    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
430    private static final int SHELL_UID = Process.SHELL_UID;
431    private static final int SE_UID = Process.SE_UID;
432
433    // Cap the size of permission trees that 3rd party apps can define
434    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
435
436    // Suffix used during package installation when copying/moving
437    // package apks to install directory.
438    private static final String INSTALL_PACKAGE_SUFFIX = "-";
439
440    static final int SCAN_NO_DEX = 1<<1;
441    static final int SCAN_FORCE_DEX = 1<<2;
442    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
443    static final int SCAN_NEW_INSTALL = 1<<4;
444    static final int SCAN_UPDATE_TIME = 1<<5;
445    static final int SCAN_BOOTING = 1<<6;
446    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
447    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
448    static final int SCAN_REPLACING = 1<<9;
449    static final int SCAN_REQUIRE_KNOWN = 1<<10;
450    static final int SCAN_MOVE = 1<<11;
451    static final int SCAN_INITIAL = 1<<12;
452    static final int SCAN_CHECK_ONLY = 1<<13;
453    static final int SCAN_DONT_KILL_APP = 1<<14;
454    static final int SCAN_IGNORE_FROZEN = 1<<15;
455    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
456    static final int SCAN_AS_INSTANT_APP = 1<<17;
457    static final int SCAN_AS_FULL_APP = 1<<18;
458    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
459    /** Should not be with the scan flags */
460    static final int FLAGS_REMOVE_CHATTY = 1<<31;
461
462    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
463    /** Extension of the compressed packages */
464    private final static String COMPRESSED_EXTENSION = ".gz";
465    /** Suffix of stub packages on the system partition */
466    private final static String STUB_SUFFIX = "-Stub";
467
468    private static final int[] EMPTY_INT_ARRAY = new int[0];
469
470    private static final int TYPE_UNKNOWN = 0;
471    private static final int TYPE_ACTIVITY = 1;
472    private static final int TYPE_RECEIVER = 2;
473    private static final int TYPE_SERVICE = 3;
474    private static final int TYPE_PROVIDER = 4;
475    @IntDef(prefix = { "TYPE_" }, value = {
476            TYPE_UNKNOWN,
477            TYPE_ACTIVITY,
478            TYPE_RECEIVER,
479            TYPE_SERVICE,
480            TYPE_PROVIDER,
481    })
482    @Retention(RetentionPolicy.SOURCE)
483    public @interface ComponentType {}
484
485    /**
486     * Timeout (in milliseconds) after which the watchdog should declare that
487     * our handler thread is wedged.  The usual default for such things is one
488     * minute but we sometimes do very lengthy I/O operations on this thread,
489     * such as installing multi-gigabyte applications, so ours needs to be longer.
490     */
491    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
492
493    /**
494     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
495     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
496     * settings entry if available, otherwise we use the hardcoded default.  If it's been
497     * more than this long since the last fstrim, we force one during the boot sequence.
498     *
499     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
500     * one gets run at the next available charging+idle time.  This final mandatory
501     * no-fstrim check kicks in only of the other scheduling criteria is never met.
502     */
503    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
504
505    /**
506     * Whether verification is enabled by default.
507     */
508    private static final boolean DEFAULT_VERIFY_ENABLE = true;
509
510    /**
511     * The default maximum time to wait for the verification agent to return in
512     * milliseconds.
513     */
514    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
515
516    /**
517     * The default response for package verification timeout.
518     *
519     * This can be either PackageManager.VERIFICATION_ALLOW or
520     * PackageManager.VERIFICATION_REJECT.
521     */
522    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
523
524    static final String PLATFORM_PACKAGE_NAME = "android";
525
526    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
527
528    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
529            DEFAULT_CONTAINER_PACKAGE,
530            "com.android.defcontainer.DefaultContainerService");
531
532    private static final String KILL_APP_REASON_GIDS_CHANGED =
533            "permission grant or revoke changed gids";
534
535    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
536            "permissions revoked";
537
538    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
539
540    private static final String PACKAGE_SCHEME = "package";
541
542    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
543
544    /** Permission grant: not grant the permission. */
545    private static final int GRANT_DENIED = 1;
546
547    /** Permission grant: grant the permission as an install permission. */
548    private static final int GRANT_INSTALL = 2;
549
550    /** Permission grant: grant the permission as a runtime one. */
551    private static final int GRANT_RUNTIME = 3;
552
553    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
554    private static final int GRANT_UPGRADE = 4;
555
556    /** Canonical intent used to identify what counts as a "web browser" app */
557    private static final Intent sBrowserIntent;
558    static {
559        sBrowserIntent = new Intent();
560        sBrowserIntent.setAction(Intent.ACTION_VIEW);
561        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
562        sBrowserIntent.setData(Uri.parse("http:"));
563    }
564
565    /**
566     * The set of all protected actions [i.e. those actions for which a high priority
567     * intent filter is disallowed].
568     */
569    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
570    static {
571        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
572        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
573        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
574        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
575    }
576
577    // Compilation reasons.
578    public static final int REASON_FIRST_BOOT = 0;
579    public static final int REASON_BOOT = 1;
580    public static final int REASON_INSTALL = 2;
581    public static final int REASON_BACKGROUND_DEXOPT = 3;
582    public static final int REASON_AB_OTA = 4;
583    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
584    public static final int REASON_SHARED = 6;
585
586    public static final int REASON_LAST = REASON_SHARED;
587
588    /** All dangerous permission names in the same order as the events in MetricsEvent */
589    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
590            Manifest.permission.READ_CALENDAR,
591            Manifest.permission.WRITE_CALENDAR,
592            Manifest.permission.CAMERA,
593            Manifest.permission.READ_CONTACTS,
594            Manifest.permission.WRITE_CONTACTS,
595            Manifest.permission.GET_ACCOUNTS,
596            Manifest.permission.ACCESS_FINE_LOCATION,
597            Manifest.permission.ACCESS_COARSE_LOCATION,
598            Manifest.permission.RECORD_AUDIO,
599            Manifest.permission.READ_PHONE_STATE,
600            Manifest.permission.CALL_PHONE,
601            Manifest.permission.READ_CALL_LOG,
602            Manifest.permission.WRITE_CALL_LOG,
603            Manifest.permission.ADD_VOICEMAIL,
604            Manifest.permission.USE_SIP,
605            Manifest.permission.PROCESS_OUTGOING_CALLS,
606            Manifest.permission.READ_CELL_BROADCASTS,
607            Manifest.permission.BODY_SENSORS,
608            Manifest.permission.SEND_SMS,
609            Manifest.permission.RECEIVE_SMS,
610            Manifest.permission.READ_SMS,
611            Manifest.permission.RECEIVE_WAP_PUSH,
612            Manifest.permission.RECEIVE_MMS,
613            Manifest.permission.READ_EXTERNAL_STORAGE,
614            Manifest.permission.WRITE_EXTERNAL_STORAGE,
615            Manifest.permission.READ_PHONE_NUMBERS,
616            Manifest.permission.ANSWER_PHONE_CALLS,
617            Manifest.permission.ACCEPT_HANDOVER);
618
619
620    /**
621     * Version number for the package parser cache. Increment this whenever the format or
622     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
623     */
624    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
625
626    /**
627     * Whether the package parser cache is enabled.
628     */
629    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
630
631    final ServiceThread mHandlerThread;
632
633    final PackageHandler mHandler;
634
635    private final ProcessLoggingHandler mProcessLoggingHandler;
636
637    /**
638     * Messages for {@link #mHandler} that need to wait for system ready before
639     * being dispatched.
640     */
641    private ArrayList<Message> mPostSystemReadyMessages;
642
643    final int mSdkVersion = Build.VERSION.SDK_INT;
644
645    final Context mContext;
646    final boolean mFactoryTest;
647    final boolean mOnlyCore;
648    final DisplayMetrics mMetrics;
649    final int mDefParseFlags;
650    final String[] mSeparateProcesses;
651    final boolean mIsUpgrade;
652    final boolean mIsPreNUpgrade;
653    final boolean mIsPreNMR1Upgrade;
654
655    // Have we told the Activity Manager to whitelist the default container service by uid yet?
656    @GuardedBy("mPackages")
657    boolean mDefaultContainerWhitelisted = false;
658
659    @GuardedBy("mPackages")
660    private boolean mDexOptDialogShown;
661
662    /** The location for ASEC container files on internal storage. */
663    final String mAsecInternalPath;
664
665    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
666    // LOCK HELD.  Can be called with mInstallLock held.
667    @GuardedBy("mInstallLock")
668    final Installer mInstaller;
669
670    /** Directory where installed third-party apps stored */
671    final File mAppInstallDir;
672
673    /**
674     * Directory to which applications installed internally have their
675     * 32 bit native libraries copied.
676     */
677    private File mAppLib32InstallDir;
678
679    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
680    // apps.
681    final File mDrmAppPrivateInstallDir;
682
683    // ----------------------------------------------------------------
684
685    // Lock for state used when installing and doing other long running
686    // operations.  Methods that must be called with this lock held have
687    // the suffix "LI".
688    final Object mInstallLock = new Object();
689
690    // ----------------------------------------------------------------
691
692    // Keys are String (package name), values are Package.  This also serves
693    // as the lock for the global state.  Methods that must be called with
694    // this lock held have the prefix "LP".
695    @GuardedBy("mPackages")
696    final ArrayMap<String, PackageParser.Package> mPackages =
697            new ArrayMap<String, PackageParser.Package>();
698
699    final ArrayMap<String, Set<String>> mKnownCodebase =
700            new ArrayMap<String, Set<String>>();
701
702    // Keys are isolated uids and values are the uid of the application
703    // that created the isolated proccess.
704    @GuardedBy("mPackages")
705    final SparseIntArray mIsolatedOwners = new SparseIntArray();
706
707    /**
708     * Tracks new system packages [received in an OTA] that we expect to
709     * find updated user-installed versions. Keys are package name, values
710     * are package location.
711     */
712    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
713    /**
714     * Tracks high priority intent filters for protected actions. During boot, certain
715     * filter actions are protected and should never be allowed to have a high priority
716     * intent filter for them. However, there is one, and only one exception -- the
717     * setup wizard. It must be able to define a high priority intent filter for these
718     * actions to ensure there are no escapes from the wizard. We need to delay processing
719     * of these during boot as we need to look at all of the system packages in order
720     * to know which component is the setup wizard.
721     */
722    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
723    /**
724     * Whether or not processing protected filters should be deferred.
725     */
726    private boolean mDeferProtectedFilters = true;
727
728    /**
729     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
730     */
731    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
732    /**
733     * Whether or not system app permissions should be promoted from install to runtime.
734     */
735    boolean mPromoteSystemApps;
736
737    @GuardedBy("mPackages")
738    final Settings mSettings;
739
740    /**
741     * Set of package names that are currently "frozen", which means active
742     * surgery is being done on the code/data for that package. The platform
743     * will refuse to launch frozen packages to avoid race conditions.
744     *
745     * @see PackageFreezer
746     */
747    @GuardedBy("mPackages")
748    final ArraySet<String> mFrozenPackages = new ArraySet<>();
749
750    final ProtectedPackages mProtectedPackages;
751
752    @GuardedBy("mLoadedVolumes")
753    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
754
755    boolean mFirstBoot;
756
757    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
758
759    // System configuration read by SystemConfig.
760    final int[] mGlobalGids;
761    final SparseArray<ArraySet<String>> mSystemPermissions;
762    @GuardedBy("mAvailableFeatures")
763    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
764
765    // If mac_permissions.xml was found for seinfo labeling.
766    boolean mFoundPolicyFile;
767
768    private final InstantAppRegistry mInstantAppRegistry;
769
770    @GuardedBy("mPackages")
771    int mChangedPackagesSequenceNumber;
772    /**
773     * List of changed [installed, removed or updated] packages.
774     * mapping from user id -> sequence number -> package name
775     */
776    @GuardedBy("mPackages")
777    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
778    /**
779     * The sequence number of the last change to a package.
780     * mapping from user id -> package name -> sequence number
781     */
782    @GuardedBy("mPackages")
783    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
784
785    class PackageParserCallback implements PackageParser.Callback {
786        @Override public final boolean hasFeature(String feature) {
787            return PackageManagerService.this.hasSystemFeature(feature, 0);
788        }
789
790        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
791                Collection<PackageParser.Package> allPackages, String targetPackageName) {
792            List<PackageParser.Package> overlayPackages = null;
793            for (PackageParser.Package p : allPackages) {
794                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
795                    if (overlayPackages == null) {
796                        overlayPackages = new ArrayList<PackageParser.Package>();
797                    }
798                    overlayPackages.add(p);
799                }
800            }
801            if (overlayPackages != null) {
802                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
803                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
804                        return p1.mOverlayPriority - p2.mOverlayPriority;
805                    }
806                };
807                Collections.sort(overlayPackages, cmp);
808            }
809            return overlayPackages;
810        }
811
812        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
813                String targetPackageName, String targetPath) {
814            if ("android".equals(targetPackageName)) {
815                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
816                // native AssetManager.
817                return null;
818            }
819            List<PackageParser.Package> overlayPackages =
820                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
821            if (overlayPackages == null || overlayPackages.isEmpty()) {
822                return null;
823            }
824            List<String> overlayPathList = null;
825            for (PackageParser.Package overlayPackage : overlayPackages) {
826                if (targetPath == null) {
827                    if (overlayPathList == null) {
828                        overlayPathList = new ArrayList<String>();
829                    }
830                    overlayPathList.add(overlayPackage.baseCodePath);
831                    continue;
832                }
833
834                try {
835                    // Creates idmaps for system to parse correctly the Android manifest of the
836                    // target package.
837                    //
838                    // OverlayManagerService will update each of them with a correct gid from its
839                    // target package app id.
840                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
841                            UserHandle.getSharedAppGid(
842                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
843                    if (overlayPathList == null) {
844                        overlayPathList = new ArrayList<String>();
845                    }
846                    overlayPathList.add(overlayPackage.baseCodePath);
847                } catch (InstallerException e) {
848                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
849                            overlayPackage.baseCodePath);
850                }
851            }
852            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
853        }
854
855        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
856            synchronized (mPackages) {
857                return getStaticOverlayPathsLocked(
858                        mPackages.values(), targetPackageName, targetPath);
859            }
860        }
861
862        @Override public final String[] getOverlayApks(String targetPackageName) {
863            return getStaticOverlayPaths(targetPackageName, null);
864        }
865
866        @Override public final String[] getOverlayPaths(String targetPackageName,
867                String targetPath) {
868            return getStaticOverlayPaths(targetPackageName, targetPath);
869        }
870    };
871
872    class ParallelPackageParserCallback extends PackageParserCallback {
873        List<PackageParser.Package> mOverlayPackages = null;
874
875        void findStaticOverlayPackages() {
876            synchronized (mPackages) {
877                for (PackageParser.Package p : mPackages.values()) {
878                    if (p.mIsStaticOverlay) {
879                        if (mOverlayPackages == null) {
880                            mOverlayPackages = new ArrayList<PackageParser.Package>();
881                        }
882                        mOverlayPackages.add(p);
883                    }
884                }
885            }
886        }
887
888        @Override
889        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
890            // We can trust mOverlayPackages without holding mPackages because package uninstall
891            // can't happen while running parallel parsing.
892            // Moreover holding mPackages on each parsing thread causes dead-lock.
893            return mOverlayPackages == null ? null :
894                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
895        }
896    }
897
898    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
899    final ParallelPackageParserCallback mParallelPackageParserCallback =
900            new ParallelPackageParserCallback();
901
902    public static final class SharedLibraryEntry {
903        public final @Nullable String path;
904        public final @Nullable String apk;
905        public final @NonNull SharedLibraryInfo info;
906
907        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
908                String declaringPackageName, int declaringPackageVersionCode) {
909            path = _path;
910            apk = _apk;
911            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
912                    declaringPackageName, declaringPackageVersionCode), null);
913        }
914    }
915
916    // Currently known shared libraries.
917    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
918    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
919            new ArrayMap<>();
920
921    // All available activities, for your resolving pleasure.
922    final ActivityIntentResolver mActivities =
923            new ActivityIntentResolver();
924
925    // All available receivers, for your resolving pleasure.
926    final ActivityIntentResolver mReceivers =
927            new ActivityIntentResolver();
928
929    // All available services, for your resolving pleasure.
930    final ServiceIntentResolver mServices = new ServiceIntentResolver();
931
932    // All available providers, for your resolving pleasure.
933    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
934
935    // Mapping from provider base names (first directory in content URI codePath)
936    // to the provider information.
937    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
938            new ArrayMap<String, PackageParser.Provider>();
939
940    // Mapping from instrumentation class names to info about them.
941    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
942            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
943
944    // Mapping from permission names to info about them.
945    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
946            new ArrayMap<String, PackageParser.PermissionGroup>();
947
948    // Packages whose data we have transfered into another package, thus
949    // should no longer exist.
950    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
951
952    // Broadcast actions that are only available to the system.
953    @GuardedBy("mProtectedBroadcasts")
954    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
955
956    /** List of packages waiting for verification. */
957    final SparseArray<PackageVerificationState> mPendingVerification
958            = new SparseArray<PackageVerificationState>();
959
960    /** Set of packages associated with each app op permission. */
961    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
962
963    final PackageInstallerService mInstallerService;
964
965    final ArtManagerService mArtManagerService;
966
967    private final PackageDexOptimizer mPackageDexOptimizer;
968    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
969    // is used by other apps).
970    private final DexManager mDexManager;
971
972    private AtomicInteger mNextMoveId = new AtomicInteger();
973    private final MoveCallbacks mMoveCallbacks;
974
975    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
976
977    // Cache of users who need badging.
978    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
979
980    /** Token for keys in mPendingVerification. */
981    private int mPendingVerificationToken = 0;
982
983    volatile boolean mSystemReady;
984    volatile boolean mSafeMode;
985    volatile boolean mHasSystemUidErrors;
986    private volatile boolean mEphemeralAppsDisabled;
987
988    ApplicationInfo mAndroidApplication;
989    final ActivityInfo mResolveActivity = new ActivityInfo();
990    final ResolveInfo mResolveInfo = new ResolveInfo();
991    ComponentName mResolveComponentName;
992    PackageParser.Package mPlatformPackage;
993    ComponentName mCustomResolverComponentName;
994
995    boolean mResolverReplaced = false;
996
997    private final @Nullable ComponentName mIntentFilterVerifierComponent;
998    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
999
1000    private int mIntentFilterVerificationToken = 0;
1001
1002    /** The service connection to the ephemeral resolver */
1003    final EphemeralResolverConnection mInstantAppResolverConnection;
1004    /** Component used to show resolver settings for Instant Apps */
1005    final ComponentName mInstantAppResolverSettingsComponent;
1006
1007    /** Activity used to install instant applications */
1008    ActivityInfo mInstantAppInstallerActivity;
1009    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1010
1011    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1012            = new SparseArray<IntentFilterVerificationState>();
1013
1014    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1015
1016    // List of packages names to keep cached, even if they are uninstalled for all users
1017    private List<String> mKeepUninstalledPackages;
1018
1019    private UserManagerInternal mUserManagerInternal;
1020
1021    private DeviceIdleController.LocalService mDeviceIdleController;
1022
1023    private File mCacheDir;
1024
1025    private ArraySet<String> mPrivappPermissionsViolations;
1026
1027    private Future<?> mPrepareAppDataFuture;
1028
1029    private static class IFVerificationParams {
1030        PackageParser.Package pkg;
1031        boolean replacing;
1032        int userId;
1033        int verifierUid;
1034
1035        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1036                int _userId, int _verifierUid) {
1037            pkg = _pkg;
1038            replacing = _replacing;
1039            userId = _userId;
1040            replacing = _replacing;
1041            verifierUid = _verifierUid;
1042        }
1043    }
1044
1045    private interface IntentFilterVerifier<T extends IntentFilter> {
1046        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1047                                               T filter, String packageName);
1048        void startVerifications(int userId);
1049        void receiveVerificationResponse(int verificationId);
1050    }
1051
1052    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1053        private Context mContext;
1054        private ComponentName mIntentFilterVerifierComponent;
1055        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1056
1057        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1058            mContext = context;
1059            mIntentFilterVerifierComponent = verifierComponent;
1060        }
1061
1062        private String getDefaultScheme() {
1063            return IntentFilter.SCHEME_HTTPS;
1064        }
1065
1066        @Override
1067        public void startVerifications(int userId) {
1068            // Launch verifications requests
1069            int count = mCurrentIntentFilterVerifications.size();
1070            for (int n=0; n<count; n++) {
1071                int verificationId = mCurrentIntentFilterVerifications.get(n);
1072                final IntentFilterVerificationState ivs =
1073                        mIntentFilterVerificationStates.get(verificationId);
1074
1075                String packageName = ivs.getPackageName();
1076
1077                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1078                final int filterCount = filters.size();
1079                ArraySet<String> domainsSet = new ArraySet<>();
1080                for (int m=0; m<filterCount; m++) {
1081                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1082                    domainsSet.addAll(filter.getHostsList());
1083                }
1084                synchronized (mPackages) {
1085                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1086                            packageName, domainsSet) != null) {
1087                        scheduleWriteSettingsLocked();
1088                    }
1089                }
1090                sendVerificationRequest(verificationId, ivs);
1091            }
1092            mCurrentIntentFilterVerifications.clear();
1093        }
1094
1095        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1096            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1097            verificationIntent.putExtra(
1098                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1099                    verificationId);
1100            verificationIntent.putExtra(
1101                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1102                    getDefaultScheme());
1103            verificationIntent.putExtra(
1104                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1105                    ivs.getHostsString());
1106            verificationIntent.putExtra(
1107                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1108                    ivs.getPackageName());
1109            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1110            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1111
1112            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1113            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1114                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1115                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1116
1117            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1118            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1119                    "Sending IntentFilter verification broadcast");
1120        }
1121
1122        public void receiveVerificationResponse(int verificationId) {
1123            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1124
1125            final boolean verified = ivs.isVerified();
1126
1127            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1128            final int count = filters.size();
1129            if (DEBUG_DOMAIN_VERIFICATION) {
1130                Slog.i(TAG, "Received verification response " + verificationId
1131                        + " for " + count + " filters, verified=" + verified);
1132            }
1133            for (int n=0; n<count; n++) {
1134                PackageParser.ActivityIntentInfo filter = filters.get(n);
1135                filter.setVerified(verified);
1136
1137                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1138                        + " verified with result:" + verified + " and hosts:"
1139                        + ivs.getHostsString());
1140            }
1141
1142            mIntentFilterVerificationStates.remove(verificationId);
1143
1144            final String packageName = ivs.getPackageName();
1145            IntentFilterVerificationInfo ivi = null;
1146
1147            synchronized (mPackages) {
1148                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1149            }
1150            if (ivi == null) {
1151                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1152                        + verificationId + " packageName:" + packageName);
1153                return;
1154            }
1155            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1156                    "Updating IntentFilterVerificationInfo for package " + packageName
1157                            +" verificationId:" + verificationId);
1158
1159            synchronized (mPackages) {
1160                if (verified) {
1161                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1162                } else {
1163                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1164                }
1165                scheduleWriteSettingsLocked();
1166
1167                final int userId = ivs.getUserId();
1168                if (userId != UserHandle.USER_ALL) {
1169                    final int userStatus =
1170                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1171
1172                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1173                    boolean needUpdate = false;
1174
1175                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1176                    // already been set by the User thru the Disambiguation dialog
1177                    switch (userStatus) {
1178                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1179                            if (verified) {
1180                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1181                            } else {
1182                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1183                            }
1184                            needUpdate = true;
1185                            break;
1186
1187                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1188                            if (verified) {
1189                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1190                                needUpdate = true;
1191                            }
1192                            break;
1193
1194                        default:
1195                            // Nothing to do
1196                    }
1197
1198                    if (needUpdate) {
1199                        mSettings.updateIntentFilterVerificationStatusLPw(
1200                                packageName, updatedStatus, userId);
1201                        scheduleWritePackageRestrictionsLocked(userId);
1202                    }
1203                }
1204            }
1205        }
1206
1207        @Override
1208        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1209                    ActivityIntentInfo filter, String packageName) {
1210            if (!hasValidDomains(filter)) {
1211                return false;
1212            }
1213            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1214            if (ivs == null) {
1215                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1216                        packageName);
1217            }
1218            if (DEBUG_DOMAIN_VERIFICATION) {
1219                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1220            }
1221            ivs.addFilter(filter);
1222            return true;
1223        }
1224
1225        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1226                int userId, int verificationId, String packageName) {
1227            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1228                    verifierUid, userId, packageName);
1229            ivs.setPendingState();
1230            synchronized (mPackages) {
1231                mIntentFilterVerificationStates.append(verificationId, ivs);
1232                mCurrentIntentFilterVerifications.add(verificationId);
1233            }
1234            return ivs;
1235        }
1236    }
1237
1238    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1239        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1240                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1241                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1242    }
1243
1244    // Set of pending broadcasts for aggregating enable/disable of components.
1245    static class PendingPackageBroadcasts {
1246        // for each user id, a map of <package name -> components within that package>
1247        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1248
1249        public PendingPackageBroadcasts() {
1250            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1251        }
1252
1253        public ArrayList<String> get(int userId, String packageName) {
1254            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1255            return packages.get(packageName);
1256        }
1257
1258        public void put(int userId, String packageName, ArrayList<String> components) {
1259            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1260            packages.put(packageName, components);
1261        }
1262
1263        public void remove(int userId, String packageName) {
1264            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1265            if (packages != null) {
1266                packages.remove(packageName);
1267            }
1268        }
1269
1270        public void remove(int userId) {
1271            mUidMap.remove(userId);
1272        }
1273
1274        public int userIdCount() {
1275            return mUidMap.size();
1276        }
1277
1278        public int userIdAt(int n) {
1279            return mUidMap.keyAt(n);
1280        }
1281
1282        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1283            return mUidMap.get(userId);
1284        }
1285
1286        public int size() {
1287            // total number of pending broadcast entries across all userIds
1288            int num = 0;
1289            for (int i = 0; i< mUidMap.size(); i++) {
1290                num += mUidMap.valueAt(i).size();
1291            }
1292            return num;
1293        }
1294
1295        public void clear() {
1296            mUidMap.clear();
1297        }
1298
1299        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1300            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1301            if (map == null) {
1302                map = new ArrayMap<String, ArrayList<String>>();
1303                mUidMap.put(userId, map);
1304            }
1305            return map;
1306        }
1307    }
1308    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1309
1310    // Service Connection to remote media container service to copy
1311    // package uri's from external media onto secure containers
1312    // or internal storage.
1313    private IMediaContainerService mContainerService = null;
1314
1315    static final int SEND_PENDING_BROADCAST = 1;
1316    static final int MCS_BOUND = 3;
1317    static final int END_COPY = 4;
1318    static final int INIT_COPY = 5;
1319    static final int MCS_UNBIND = 6;
1320    static final int START_CLEANING_PACKAGE = 7;
1321    static final int FIND_INSTALL_LOC = 8;
1322    static final int POST_INSTALL = 9;
1323    static final int MCS_RECONNECT = 10;
1324    static final int MCS_GIVE_UP = 11;
1325    static final int UPDATED_MEDIA_STATUS = 12;
1326    static final int WRITE_SETTINGS = 13;
1327    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1328    static final int PACKAGE_VERIFIED = 15;
1329    static final int CHECK_PENDING_VERIFICATION = 16;
1330    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1331    static final int INTENT_FILTER_VERIFIED = 18;
1332    static final int WRITE_PACKAGE_LIST = 19;
1333    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1334
1335    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1336
1337    // Delay time in millisecs
1338    static final int BROADCAST_DELAY = 10 * 1000;
1339
1340    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1341            2 * 60 * 60 * 1000L; /* two hours */
1342
1343    static UserManagerService sUserManager;
1344
1345    // Stores a list of users whose package restrictions file needs to be updated
1346    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1347
1348    final private DefaultContainerConnection mDefContainerConn =
1349            new DefaultContainerConnection();
1350    class DefaultContainerConnection implements ServiceConnection {
1351        public void onServiceConnected(ComponentName name, IBinder service) {
1352            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1353            final IMediaContainerService imcs = IMediaContainerService.Stub
1354                    .asInterface(Binder.allowBlocking(service));
1355            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1356        }
1357
1358        public void onServiceDisconnected(ComponentName name) {
1359            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1360        }
1361    }
1362
1363    // Recordkeeping of restore-after-install operations that are currently in flight
1364    // between the Package Manager and the Backup Manager
1365    static class PostInstallData {
1366        public InstallArgs args;
1367        public PackageInstalledInfo res;
1368
1369        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1370            args = _a;
1371            res = _r;
1372        }
1373    }
1374
1375    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1376    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1377
1378    // XML tags for backup/restore of various bits of state
1379    private static final String TAG_PREFERRED_BACKUP = "pa";
1380    private static final String TAG_DEFAULT_APPS = "da";
1381    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1382
1383    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1384    private static final String TAG_ALL_GRANTS = "rt-grants";
1385    private static final String TAG_GRANT = "grant";
1386    private static final String ATTR_PACKAGE_NAME = "pkg";
1387
1388    private static final String TAG_PERMISSION = "perm";
1389    private static final String ATTR_PERMISSION_NAME = "name";
1390    private static final String ATTR_IS_GRANTED = "g";
1391    private static final String ATTR_USER_SET = "set";
1392    private static final String ATTR_USER_FIXED = "fixed";
1393    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1394
1395    // System/policy permission grants are not backed up
1396    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1397            FLAG_PERMISSION_POLICY_FIXED
1398            | FLAG_PERMISSION_SYSTEM_FIXED
1399            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1400
1401    // And we back up these user-adjusted states
1402    private static final int USER_RUNTIME_GRANT_MASK =
1403            FLAG_PERMISSION_USER_SET
1404            | FLAG_PERMISSION_USER_FIXED
1405            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1406
1407    final @Nullable String mRequiredVerifierPackage;
1408    final @NonNull String mRequiredInstallerPackage;
1409    final @NonNull String mRequiredUninstallerPackage;
1410    final @Nullable String mSetupWizardPackage;
1411    final @Nullable String mStorageManagerPackage;
1412    final @NonNull String mServicesSystemSharedLibraryPackageName;
1413    final @NonNull String mSharedSystemSharedLibraryPackageName;
1414
1415    final boolean mPermissionReviewRequired;
1416
1417    private final PackageUsage mPackageUsage = new PackageUsage();
1418    private final CompilerStats mCompilerStats = new CompilerStats();
1419
1420    class PackageHandler extends Handler {
1421        private boolean mBound = false;
1422        final ArrayList<HandlerParams> mPendingInstalls =
1423            new ArrayList<HandlerParams>();
1424
1425        private boolean connectToService() {
1426            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1427                    " DefaultContainerService");
1428            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1430            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1431                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1432                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433                mBound = true;
1434                return true;
1435            }
1436            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1437            return false;
1438        }
1439
1440        private void disconnectService() {
1441            mContainerService = null;
1442            mBound = false;
1443            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1444            mContext.unbindService(mDefContainerConn);
1445            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1446        }
1447
1448        PackageHandler(Looper looper) {
1449            super(looper);
1450        }
1451
1452        public void handleMessage(Message msg) {
1453            try {
1454                doHandleMessage(msg);
1455            } finally {
1456                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1457            }
1458        }
1459
1460        void doHandleMessage(Message msg) {
1461            switch (msg.what) {
1462                case INIT_COPY: {
1463                    HandlerParams params = (HandlerParams) msg.obj;
1464                    int idx = mPendingInstalls.size();
1465                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1466                    // If a bind was already initiated we dont really
1467                    // need to do anything. The pending install
1468                    // will be processed later on.
1469                    if (!mBound) {
1470                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1471                                System.identityHashCode(mHandler));
1472                        // If this is the only one pending we might
1473                        // have to bind to the service again.
1474                        if (!connectToService()) {
1475                            Slog.e(TAG, "Failed to bind to media container service");
1476                            params.serviceError();
1477                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1478                                    System.identityHashCode(mHandler));
1479                            if (params.traceMethod != null) {
1480                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1481                                        params.traceCookie);
1482                            }
1483                            return;
1484                        } else {
1485                            // Once we bind to the service, the first
1486                            // pending request will be processed.
1487                            mPendingInstalls.add(idx, params);
1488                        }
1489                    } else {
1490                        mPendingInstalls.add(idx, params);
1491                        // Already bound to the service. Just make
1492                        // sure we trigger off processing the first request.
1493                        if (idx == 0) {
1494                            mHandler.sendEmptyMessage(MCS_BOUND);
1495                        }
1496                    }
1497                    break;
1498                }
1499                case MCS_BOUND: {
1500                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1501                    if (msg.obj != null) {
1502                        mContainerService = (IMediaContainerService) msg.obj;
1503                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1504                                System.identityHashCode(mHandler));
1505                    }
1506                    if (mContainerService == null) {
1507                        if (!mBound) {
1508                            // Something seriously wrong since we are not bound and we are not
1509                            // waiting for connection. Bail out.
1510                            Slog.e(TAG, "Cannot bind to media container service");
1511                            for (HandlerParams params : mPendingInstalls) {
1512                                // Indicate service bind error
1513                                params.serviceError();
1514                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1515                                        System.identityHashCode(params));
1516                                if (params.traceMethod != null) {
1517                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1518                                            params.traceMethod, params.traceCookie);
1519                                }
1520                                return;
1521                            }
1522                            mPendingInstalls.clear();
1523                        } else {
1524                            Slog.w(TAG, "Waiting to connect to media container service");
1525                        }
1526                    } else if (mPendingInstalls.size() > 0) {
1527                        HandlerParams params = mPendingInstalls.get(0);
1528                        if (params != null) {
1529                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1530                                    System.identityHashCode(params));
1531                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1532                            if (params.startCopy()) {
1533                                // We are done...  look for more work or to
1534                                // go idle.
1535                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1536                                        "Checking for more work or unbind...");
1537                                // Delete pending install
1538                                if (mPendingInstalls.size() > 0) {
1539                                    mPendingInstalls.remove(0);
1540                                }
1541                                if (mPendingInstalls.size() == 0) {
1542                                    if (mBound) {
1543                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1544                                                "Posting delayed MCS_UNBIND");
1545                                        removeMessages(MCS_UNBIND);
1546                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1547                                        // Unbind after a little delay, to avoid
1548                                        // continual thrashing.
1549                                        sendMessageDelayed(ubmsg, 10000);
1550                                    }
1551                                } else {
1552                                    // There are more pending requests in queue.
1553                                    // Just post MCS_BOUND message to trigger processing
1554                                    // of next pending install.
1555                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1556                                            "Posting MCS_BOUND for next work");
1557                                    mHandler.sendEmptyMessage(MCS_BOUND);
1558                                }
1559                            }
1560                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1561                        }
1562                    } else {
1563                        // Should never happen ideally.
1564                        Slog.w(TAG, "Empty queue");
1565                    }
1566                    break;
1567                }
1568                case MCS_RECONNECT: {
1569                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1570                    if (mPendingInstalls.size() > 0) {
1571                        if (mBound) {
1572                            disconnectService();
1573                        }
1574                        if (!connectToService()) {
1575                            Slog.e(TAG, "Failed to bind to media container service");
1576                            for (HandlerParams params : mPendingInstalls) {
1577                                // Indicate service bind error
1578                                params.serviceError();
1579                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1580                                        System.identityHashCode(params));
1581                            }
1582                            mPendingInstalls.clear();
1583                        }
1584                    }
1585                    break;
1586                }
1587                case MCS_UNBIND: {
1588                    // If there is no actual work left, then time to unbind.
1589                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1590
1591                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1592                        if (mBound) {
1593                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1594
1595                            disconnectService();
1596                        }
1597                    } else if (mPendingInstalls.size() > 0) {
1598                        // There are more pending requests in queue.
1599                        // Just post MCS_BOUND message to trigger processing
1600                        // of next pending install.
1601                        mHandler.sendEmptyMessage(MCS_BOUND);
1602                    }
1603
1604                    break;
1605                }
1606                case MCS_GIVE_UP: {
1607                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1608                    HandlerParams params = mPendingInstalls.remove(0);
1609                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1610                            System.identityHashCode(params));
1611                    break;
1612                }
1613                case SEND_PENDING_BROADCAST: {
1614                    String packages[];
1615                    ArrayList<String> components[];
1616                    int size = 0;
1617                    int uids[];
1618                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1619                    synchronized (mPackages) {
1620                        if (mPendingBroadcasts == null) {
1621                            return;
1622                        }
1623                        size = mPendingBroadcasts.size();
1624                        if (size <= 0) {
1625                            // Nothing to be done. Just return
1626                            return;
1627                        }
1628                        packages = new String[size];
1629                        components = new ArrayList[size];
1630                        uids = new int[size];
1631                        int i = 0;  // filling out the above arrays
1632
1633                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1634                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1635                            Iterator<Map.Entry<String, ArrayList<String>>> it
1636                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1637                                            .entrySet().iterator();
1638                            while (it.hasNext() && i < size) {
1639                                Map.Entry<String, ArrayList<String>> ent = it.next();
1640                                packages[i] = ent.getKey();
1641                                components[i] = ent.getValue();
1642                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1643                                uids[i] = (ps != null)
1644                                        ? UserHandle.getUid(packageUserId, ps.appId)
1645                                        : -1;
1646                                i++;
1647                            }
1648                        }
1649                        size = i;
1650                        mPendingBroadcasts.clear();
1651                    }
1652                    // Send broadcasts
1653                    for (int i = 0; i < size; i++) {
1654                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1655                    }
1656                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1657                    break;
1658                }
1659                case START_CLEANING_PACKAGE: {
1660                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1661                    final String packageName = (String)msg.obj;
1662                    final int userId = msg.arg1;
1663                    final boolean andCode = msg.arg2 != 0;
1664                    synchronized (mPackages) {
1665                        if (userId == UserHandle.USER_ALL) {
1666                            int[] users = sUserManager.getUserIds();
1667                            for (int user : users) {
1668                                mSettings.addPackageToCleanLPw(
1669                                        new PackageCleanItem(user, packageName, andCode));
1670                            }
1671                        } else {
1672                            mSettings.addPackageToCleanLPw(
1673                                    new PackageCleanItem(userId, packageName, andCode));
1674                        }
1675                    }
1676                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1677                    startCleaningPackages();
1678                } break;
1679                case POST_INSTALL: {
1680                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1681
1682                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1683                    final boolean didRestore = (msg.arg2 != 0);
1684                    mRunningInstalls.delete(msg.arg1);
1685
1686                    if (data != null) {
1687                        InstallArgs args = data.args;
1688                        PackageInstalledInfo parentRes = data.res;
1689
1690                        final boolean grantPermissions = (args.installFlags
1691                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1692                        final boolean killApp = (args.installFlags
1693                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1694                        final boolean virtualPreload = ((args.installFlags
1695                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1696                        final String[] grantedPermissions = args.installGrantPermissions;
1697
1698                        // Handle the parent package
1699                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1700                                virtualPreload, grantedPermissions, didRestore,
1701                                args.installerPackageName, args.observer);
1702
1703                        // Handle the child packages
1704                        final int childCount = (parentRes.addedChildPackages != null)
1705                                ? parentRes.addedChildPackages.size() : 0;
1706                        for (int i = 0; i < childCount; i++) {
1707                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1708                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1709                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1710                                    args.installerPackageName, args.observer);
1711                        }
1712
1713                        // Log tracing if needed
1714                        if (args.traceMethod != null) {
1715                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1716                                    args.traceCookie);
1717                        }
1718                    } else {
1719                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1720                    }
1721
1722                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1723                } break;
1724                case UPDATED_MEDIA_STATUS: {
1725                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1726                    boolean reportStatus = msg.arg1 == 1;
1727                    boolean doGc = msg.arg2 == 1;
1728                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1729                    if (doGc) {
1730                        // Force a gc to clear up stale containers.
1731                        Runtime.getRuntime().gc();
1732                    }
1733                    if (msg.obj != null) {
1734                        @SuppressWarnings("unchecked")
1735                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1736                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1737                        // Unload containers
1738                        unloadAllContainers(args);
1739                    }
1740                    if (reportStatus) {
1741                        try {
1742                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1743                                    "Invoking StorageManagerService call back");
1744                            PackageHelper.getStorageManager().finishMediaUpdate();
1745                        } catch (RemoteException e) {
1746                            Log.e(TAG, "StorageManagerService not running?");
1747                        }
1748                    }
1749                } break;
1750                case WRITE_SETTINGS: {
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1752                    synchronized (mPackages) {
1753                        removeMessages(WRITE_SETTINGS);
1754                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1755                        mSettings.writeLPr();
1756                        mDirtyUsers.clear();
1757                    }
1758                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1759                } break;
1760                case WRITE_PACKAGE_RESTRICTIONS: {
1761                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1762                    synchronized (mPackages) {
1763                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1764                        for (int userId : mDirtyUsers) {
1765                            mSettings.writePackageRestrictionsLPr(userId);
1766                        }
1767                        mDirtyUsers.clear();
1768                    }
1769                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1770                } break;
1771                case WRITE_PACKAGE_LIST: {
1772                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1773                    synchronized (mPackages) {
1774                        removeMessages(WRITE_PACKAGE_LIST);
1775                        mSettings.writePackageListLPr(msg.arg1);
1776                    }
1777                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1778                } break;
1779                case CHECK_PENDING_VERIFICATION: {
1780                    final int verificationId = msg.arg1;
1781                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1782
1783                    if ((state != null) && !state.timeoutExtended()) {
1784                        final InstallArgs args = state.getInstallArgs();
1785                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1786
1787                        Slog.i(TAG, "Verification timed out for " + originUri);
1788                        mPendingVerification.remove(verificationId);
1789
1790                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1791
1792                        final UserHandle user = args.getUser();
1793                        if (getDefaultVerificationResponse(user)
1794                                == PackageManager.VERIFICATION_ALLOW) {
1795                            Slog.i(TAG, "Continuing with installation of " + originUri);
1796                            state.setVerifierResponse(Binder.getCallingUid(),
1797                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1798                            broadcastPackageVerified(verificationId, originUri,
1799                                    PackageManager.VERIFICATION_ALLOW, user);
1800                            try {
1801                                ret = args.copyApk(mContainerService, true);
1802                            } catch (RemoteException e) {
1803                                Slog.e(TAG, "Could not contact the ContainerService");
1804                            }
1805                        } else {
1806                            broadcastPackageVerified(verificationId, originUri,
1807                                    PackageManager.VERIFICATION_REJECT, user);
1808                        }
1809
1810                        Trace.asyncTraceEnd(
1811                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1812
1813                        processPendingInstall(args, ret);
1814                        mHandler.sendEmptyMessage(MCS_UNBIND);
1815                    }
1816                    break;
1817                }
1818                case PACKAGE_VERIFIED: {
1819                    final int verificationId = msg.arg1;
1820
1821                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1822                    if (state == null) {
1823                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1824                        break;
1825                    }
1826
1827                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1828
1829                    state.setVerifierResponse(response.callerUid, response.code);
1830
1831                    if (state.isVerificationComplete()) {
1832                        mPendingVerification.remove(verificationId);
1833
1834                        final InstallArgs args = state.getInstallArgs();
1835                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1836
1837                        int ret;
1838                        if (state.isInstallAllowed()) {
1839                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1840                            broadcastPackageVerified(verificationId, originUri,
1841                                    response.code, state.getInstallArgs().getUser());
1842                            try {
1843                                ret = args.copyApk(mContainerService, true);
1844                            } catch (RemoteException e) {
1845                                Slog.e(TAG, "Could not contact the ContainerService");
1846                            }
1847                        } else {
1848                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1849                        }
1850
1851                        Trace.asyncTraceEnd(
1852                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1853
1854                        processPendingInstall(args, ret);
1855                        mHandler.sendEmptyMessage(MCS_UNBIND);
1856                    }
1857
1858                    break;
1859                }
1860                case START_INTENT_FILTER_VERIFICATIONS: {
1861                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1862                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1863                            params.replacing, params.pkg);
1864                    break;
1865                }
1866                case INTENT_FILTER_VERIFIED: {
1867                    final int verificationId = msg.arg1;
1868
1869                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1870                            verificationId);
1871                    if (state == null) {
1872                        Slog.w(TAG, "Invalid IntentFilter verification token "
1873                                + verificationId + " received");
1874                        break;
1875                    }
1876
1877                    final int userId = state.getUserId();
1878
1879                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1880                            "Processing IntentFilter verification with token:"
1881                            + verificationId + " and userId:" + userId);
1882
1883                    final IntentFilterVerificationResponse response =
1884                            (IntentFilterVerificationResponse) msg.obj;
1885
1886                    state.setVerifierResponse(response.callerUid, response.code);
1887
1888                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1889                            "IntentFilter verification with token:" + verificationId
1890                            + " and userId:" + userId
1891                            + " is settings verifier response with response code:"
1892                            + response.code);
1893
1894                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1895                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1896                                + response.getFailedDomainsString());
1897                    }
1898
1899                    if (state.isVerificationComplete()) {
1900                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1901                    } else {
1902                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1903                                "IntentFilter verification with token:" + verificationId
1904                                + " was not said to be complete");
1905                    }
1906
1907                    break;
1908                }
1909                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1910                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1911                            mInstantAppResolverConnection,
1912                            (InstantAppRequest) msg.obj,
1913                            mInstantAppInstallerActivity,
1914                            mHandler);
1915                }
1916            }
1917        }
1918    }
1919
1920    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1921            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1922            boolean launchedForRestore, String installerPackage,
1923            IPackageInstallObserver2 installObserver) {
1924        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1925            // Send the removed broadcasts
1926            if (res.removedInfo != null) {
1927                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1928            }
1929
1930            // Now that we successfully installed the package, grant runtime
1931            // permissions if requested before broadcasting the install. Also
1932            // for legacy apps in permission review mode we clear the permission
1933            // review flag which is used to emulate runtime permissions for
1934            // legacy apps.
1935            if (grantPermissions) {
1936                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1937            }
1938
1939            final boolean update = res.removedInfo != null
1940                    && res.removedInfo.removedPackage != null;
1941            final String installerPackageName =
1942                    res.installerPackageName != null
1943                            ? res.installerPackageName
1944                            : res.removedInfo != null
1945                                    ? res.removedInfo.installerPackageName
1946                                    : null;
1947
1948            // If this is the first time we have child packages for a disabled privileged
1949            // app that had no children, we grant requested runtime permissions to the new
1950            // children if the parent on the system image had them already granted.
1951            if (res.pkg.parentPackage != null) {
1952                synchronized (mPackages) {
1953                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1954                }
1955            }
1956
1957            synchronized (mPackages) {
1958                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1959            }
1960
1961            final String packageName = res.pkg.applicationInfo.packageName;
1962
1963            // Determine the set of users who are adding this package for
1964            // the first time vs. those who are seeing an update.
1965            int[] firstUsers = EMPTY_INT_ARRAY;
1966            int[] updateUsers = EMPTY_INT_ARRAY;
1967            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1968            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1969            for (int newUser : res.newUsers) {
1970                if (ps.getInstantApp(newUser)) {
1971                    continue;
1972                }
1973                if (allNewUsers) {
1974                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1975                    continue;
1976                }
1977                boolean isNew = true;
1978                for (int origUser : res.origUsers) {
1979                    if (origUser == newUser) {
1980                        isNew = false;
1981                        break;
1982                    }
1983                }
1984                if (isNew) {
1985                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1986                } else {
1987                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1988                }
1989            }
1990
1991            // Send installed broadcasts if the package is not a static shared lib.
1992            if (res.pkg.staticSharedLibName == null) {
1993                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1994
1995                // Send added for users that see the package for the first time
1996                // sendPackageAddedForNewUsers also deals with system apps
1997                int appId = UserHandle.getAppId(res.uid);
1998                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1999                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2000                        virtualPreload /*startReceiver*/, appId, firstUsers);
2001
2002                // Send added for users that don't see the package for the first time
2003                Bundle extras = new Bundle(1);
2004                extras.putInt(Intent.EXTRA_UID, res.uid);
2005                if (update) {
2006                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2007                }
2008                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2009                        extras, 0 /*flags*/,
2010                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2011                if (installerPackageName != null) {
2012                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2013                            extras, 0 /*flags*/,
2014                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2015                }
2016
2017                // Send replaced for users that don't see the package for the first time
2018                if (update) {
2019                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2020                            packageName, extras, 0 /*flags*/,
2021                            null /*targetPackage*/, null /*finishedReceiver*/,
2022                            updateUsers);
2023                    if (installerPackageName != null) {
2024                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2025                                extras, 0 /*flags*/,
2026                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2027                    }
2028                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2029                            null /*package*/, null /*extras*/, 0 /*flags*/,
2030                            packageName /*targetPackage*/,
2031                            null /*finishedReceiver*/, updateUsers);
2032                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2033                    // First-install and we did a restore, so we're responsible for the
2034                    // first-launch broadcast.
2035                    if (DEBUG_BACKUP) {
2036                        Slog.i(TAG, "Post-restore of " + packageName
2037                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2038                    }
2039                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2040                }
2041
2042                // Send broadcast package appeared if forward locked/external for all users
2043                // treat asec-hosted packages like removable media on upgrade
2044                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2045                    if (DEBUG_INSTALL) {
2046                        Slog.i(TAG, "upgrading pkg " + res.pkg
2047                                + " is ASEC-hosted -> AVAILABLE");
2048                    }
2049                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2050                    ArrayList<String> pkgList = new ArrayList<>(1);
2051                    pkgList.add(packageName);
2052                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2053                }
2054            }
2055
2056            // Work that needs to happen on first install within each user
2057            if (firstUsers != null && firstUsers.length > 0) {
2058                synchronized (mPackages) {
2059                    for (int userId : firstUsers) {
2060                        // If this app is a browser and it's newly-installed for some
2061                        // users, clear any default-browser state in those users. The
2062                        // app's nature doesn't depend on the user, so we can just check
2063                        // its browser nature in any user and generalize.
2064                        if (packageIsBrowser(packageName, userId)) {
2065                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2066                        }
2067
2068                        // We may also need to apply pending (restored) runtime
2069                        // permission grants within these users.
2070                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2071                    }
2072                }
2073            }
2074
2075            // Log current value of "unknown sources" setting
2076            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2077                    getUnknownSourcesSettings());
2078
2079            // Remove the replaced package's older resources safely now
2080            // We delete after a gc for applications  on sdcard.
2081            if (res.removedInfo != null && res.removedInfo.args != null) {
2082                Runtime.getRuntime().gc();
2083                synchronized (mInstallLock) {
2084                    res.removedInfo.args.doPostDeleteLI(true);
2085                }
2086            } else {
2087                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2088                // and not block here.
2089                VMRuntime.getRuntime().requestConcurrentGC();
2090            }
2091
2092            // Notify DexManager that the package was installed for new users.
2093            // The updated users should already be indexed and the package code paths
2094            // should not change.
2095            // Don't notify the manager for ephemeral apps as they are not expected to
2096            // survive long enough to benefit of background optimizations.
2097            for (int userId : firstUsers) {
2098                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2099                // There's a race currently where some install events may interleave with an uninstall.
2100                // This can lead to package info being null (b/36642664).
2101                if (info != null) {
2102                    mDexManager.notifyPackageInstalled(info, userId);
2103                }
2104            }
2105        }
2106
2107        // If someone is watching installs - notify them
2108        if (installObserver != null) {
2109            try {
2110                Bundle extras = extrasForInstallResult(res);
2111                installObserver.onPackageInstalled(res.name, res.returnCode,
2112                        res.returnMsg, extras);
2113            } catch (RemoteException e) {
2114                Slog.i(TAG, "Observer no longer exists.");
2115            }
2116        }
2117    }
2118
2119    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2120            PackageParser.Package pkg) {
2121        if (pkg.parentPackage == null) {
2122            return;
2123        }
2124        if (pkg.requestedPermissions == null) {
2125            return;
2126        }
2127        final PackageSetting disabledSysParentPs = mSettings
2128                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2129        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2130                || !disabledSysParentPs.isPrivileged()
2131                || (disabledSysParentPs.childPackageNames != null
2132                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2133            return;
2134        }
2135        final int[] allUserIds = sUserManager.getUserIds();
2136        final int permCount = pkg.requestedPermissions.size();
2137        for (int i = 0; i < permCount; i++) {
2138            String permission = pkg.requestedPermissions.get(i);
2139            BasePermission bp = mSettings.mPermissions.get(permission);
2140            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2141                continue;
2142            }
2143            for (int userId : allUserIds) {
2144                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2145                        permission, userId)) {
2146                    grantRuntimePermission(pkg.packageName, permission, userId);
2147                }
2148            }
2149        }
2150    }
2151
2152    private StorageEventListener mStorageListener = new StorageEventListener() {
2153        @Override
2154        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2155            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2156                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2157                    final String volumeUuid = vol.getFsUuid();
2158
2159                    // Clean up any users or apps that were removed or recreated
2160                    // while this volume was missing
2161                    sUserManager.reconcileUsers(volumeUuid);
2162                    reconcileApps(volumeUuid);
2163
2164                    // Clean up any install sessions that expired or were
2165                    // cancelled while this volume was missing
2166                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2167
2168                    loadPrivatePackages(vol);
2169
2170                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2171                    unloadPrivatePackages(vol);
2172                }
2173            }
2174
2175            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2176                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2177                    updateExternalMediaStatus(true, false);
2178                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2179                    updateExternalMediaStatus(false, false);
2180                }
2181            }
2182        }
2183
2184        @Override
2185        public void onVolumeForgotten(String fsUuid) {
2186            if (TextUtils.isEmpty(fsUuid)) {
2187                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2188                return;
2189            }
2190
2191            // Remove any apps installed on the forgotten volume
2192            synchronized (mPackages) {
2193                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2194                for (PackageSetting ps : packages) {
2195                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2196                    deletePackageVersioned(new VersionedPackage(ps.name,
2197                            PackageManager.VERSION_CODE_HIGHEST),
2198                            new LegacyPackageDeleteObserver(null).getBinder(),
2199                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2200                    // Try very hard to release any references to this package
2201                    // so we don't risk the system server being killed due to
2202                    // open FDs
2203                    AttributeCache.instance().removePackage(ps.name);
2204                }
2205
2206                mSettings.onVolumeForgotten(fsUuid);
2207                mSettings.writeLPr();
2208            }
2209        }
2210    };
2211
2212    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2213            String[] grantedPermissions) {
2214        for (int userId : userIds) {
2215            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2216        }
2217    }
2218
2219    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2220            String[] grantedPermissions) {
2221        PackageSetting ps = (PackageSetting) pkg.mExtras;
2222        if (ps == null) {
2223            return;
2224        }
2225
2226        PermissionsState permissionsState = ps.getPermissionsState();
2227
2228        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2229                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2230
2231        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2232                >= Build.VERSION_CODES.M;
2233
2234        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2235
2236        for (String permission : pkg.requestedPermissions) {
2237            final BasePermission bp;
2238            synchronized (mPackages) {
2239                bp = mSettings.mPermissions.get(permission);
2240            }
2241            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2242                    && (!instantApp || bp.isInstant())
2243                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2244                    && (grantedPermissions == null
2245                           || ArrayUtils.contains(grantedPermissions, permission))) {
2246                final int flags = permissionsState.getPermissionFlags(permission, userId);
2247                if (supportsRuntimePermissions) {
2248                    // Installer cannot change immutable permissions.
2249                    if ((flags & immutableFlags) == 0) {
2250                        grantRuntimePermission(pkg.packageName, permission, userId);
2251                    }
2252                } else if (mPermissionReviewRequired) {
2253                    // In permission review mode we clear the review flag when we
2254                    // are asked to install the app with all permissions granted.
2255                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2256                        updatePermissionFlags(permission, pkg.packageName,
2257                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2258                    }
2259                }
2260            }
2261        }
2262    }
2263
2264    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2265        Bundle extras = null;
2266        switch (res.returnCode) {
2267            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2268                extras = new Bundle();
2269                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2270                        res.origPermission);
2271                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2272                        res.origPackage);
2273                break;
2274            }
2275            case PackageManager.INSTALL_SUCCEEDED: {
2276                extras = new Bundle();
2277                extras.putBoolean(Intent.EXTRA_REPLACING,
2278                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2279                break;
2280            }
2281        }
2282        return extras;
2283    }
2284
2285    void scheduleWriteSettingsLocked() {
2286        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2287            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2288        }
2289    }
2290
2291    void scheduleWritePackageListLocked(int userId) {
2292        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2293            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2294            msg.arg1 = userId;
2295            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2296        }
2297    }
2298
2299    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2300        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2301        scheduleWritePackageRestrictionsLocked(userId);
2302    }
2303
2304    void scheduleWritePackageRestrictionsLocked(int userId) {
2305        final int[] userIds = (userId == UserHandle.USER_ALL)
2306                ? sUserManager.getUserIds() : new int[]{userId};
2307        for (int nextUserId : userIds) {
2308            if (!sUserManager.exists(nextUserId)) return;
2309            mDirtyUsers.add(nextUserId);
2310            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2311                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2312            }
2313        }
2314    }
2315
2316    public static PackageManagerService main(Context context, Installer installer,
2317            boolean factoryTest, boolean onlyCore) {
2318        // Self-check for initial settings.
2319        PackageManagerServiceCompilerMapping.checkProperties();
2320
2321        PackageManagerService m = new PackageManagerService(context, installer,
2322                factoryTest, onlyCore);
2323        m.enableSystemUserPackages();
2324        ServiceManager.addService("package", m);
2325        final PackageManagerNative pmn = m.new PackageManagerNative();
2326        ServiceManager.addService("package_native", pmn);
2327        return m;
2328    }
2329
2330    private void enableSystemUserPackages() {
2331        if (!UserManager.isSplitSystemUser()) {
2332            return;
2333        }
2334        // For system user, enable apps based on the following conditions:
2335        // - app is whitelisted or belong to one of these groups:
2336        //   -- system app which has no launcher icons
2337        //   -- system app which has INTERACT_ACROSS_USERS permission
2338        //   -- system IME app
2339        // - app is not in the blacklist
2340        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2341        Set<String> enableApps = new ArraySet<>();
2342        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2343                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2344                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2345        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2346        enableApps.addAll(wlApps);
2347        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2348                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2349        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2350        enableApps.removeAll(blApps);
2351        Log.i(TAG, "Applications installed for system user: " + enableApps);
2352        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2353                UserHandle.SYSTEM);
2354        final int allAppsSize = allAps.size();
2355        synchronized (mPackages) {
2356            for (int i = 0; i < allAppsSize; i++) {
2357                String pName = allAps.get(i);
2358                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2359                // Should not happen, but we shouldn't be failing if it does
2360                if (pkgSetting == null) {
2361                    continue;
2362                }
2363                boolean install = enableApps.contains(pName);
2364                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2365                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2366                            + " for system user");
2367                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2368                }
2369            }
2370            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2371        }
2372    }
2373
2374    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2375        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2376                Context.DISPLAY_SERVICE);
2377        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2378    }
2379
2380    /**
2381     * Requests that files preopted on a secondary system partition be copied to the data partition
2382     * if possible.  Note that the actual copying of the files is accomplished by init for security
2383     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2384     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2385     */
2386    private static void requestCopyPreoptedFiles() {
2387        final int WAIT_TIME_MS = 100;
2388        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2389        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2390            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2391            // We will wait for up to 100 seconds.
2392            final long timeStart = SystemClock.uptimeMillis();
2393            final long timeEnd = timeStart + 100 * 1000;
2394            long timeNow = timeStart;
2395            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2396                try {
2397                    Thread.sleep(WAIT_TIME_MS);
2398                } catch (InterruptedException e) {
2399                    // Do nothing
2400                }
2401                timeNow = SystemClock.uptimeMillis();
2402                if (timeNow > timeEnd) {
2403                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2404                    Slog.wtf(TAG, "cppreopt did not finish!");
2405                    break;
2406                }
2407            }
2408
2409            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2410        }
2411    }
2412
2413    public PackageManagerService(Context context, Installer installer,
2414            boolean factoryTest, boolean onlyCore) {
2415        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2416        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2417        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2418                SystemClock.uptimeMillis());
2419
2420        if (mSdkVersion <= 0) {
2421            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2422        }
2423
2424        mContext = context;
2425
2426        mPermissionReviewRequired = context.getResources().getBoolean(
2427                R.bool.config_permissionReviewRequired);
2428
2429        mFactoryTest = factoryTest;
2430        mOnlyCore = onlyCore;
2431        mMetrics = new DisplayMetrics();
2432        mSettings = new Settings(mPackages);
2433        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2434                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2435        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2436                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2437        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2438                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2439        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2440                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2441        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2442                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2443        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2444                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2445        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2446                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2447
2448        String separateProcesses = SystemProperties.get("debug.separate_processes");
2449        if (separateProcesses != null && separateProcesses.length() > 0) {
2450            if ("*".equals(separateProcesses)) {
2451                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2452                mSeparateProcesses = null;
2453                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2454            } else {
2455                mDefParseFlags = 0;
2456                mSeparateProcesses = separateProcesses.split(",");
2457                Slog.w(TAG, "Running with debug.separate_processes: "
2458                        + separateProcesses);
2459            }
2460        } else {
2461            mDefParseFlags = 0;
2462            mSeparateProcesses = null;
2463        }
2464
2465        mInstaller = installer;
2466        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2467                "*dexopt*");
2468        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2469                installer, mInstallLock);
2470        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2471                dexManagerListener);
2472        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2473        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2474
2475        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2476                FgThread.get().getLooper());
2477
2478        getDefaultDisplayMetrics(context, mMetrics);
2479
2480        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2481        SystemConfig systemConfig = SystemConfig.getInstance();
2482        mGlobalGids = systemConfig.getGlobalGids();
2483        mSystemPermissions = systemConfig.getSystemPermissions();
2484        mAvailableFeatures = systemConfig.getAvailableFeatures();
2485        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2486
2487        mProtectedPackages = new ProtectedPackages(mContext);
2488
2489        synchronized (mInstallLock) {
2490        // writer
2491        synchronized (mPackages) {
2492            mHandlerThread = new ServiceThread(TAG,
2493                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2494            mHandlerThread.start();
2495            mHandler = new PackageHandler(mHandlerThread.getLooper());
2496            mProcessLoggingHandler = new ProcessLoggingHandler();
2497            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2498
2499            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2500            mInstantAppRegistry = new InstantAppRegistry(this);
2501
2502            File dataDir = Environment.getDataDirectory();
2503            mAppInstallDir = new File(dataDir, "app");
2504            mAppLib32InstallDir = new File(dataDir, "app-lib");
2505            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2506            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2507            sUserManager = new UserManagerService(context, this,
2508                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2509
2510            // Propagate permission configuration in to package manager.
2511            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2512                    = systemConfig.getPermissions();
2513            for (int i=0; i<permConfig.size(); i++) {
2514                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2515                BasePermission bp = mSettings.mPermissions.get(perm.name);
2516                if (bp == null) {
2517                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2518                    mSettings.mPermissions.put(perm.name, bp);
2519                }
2520                if (perm.gids != null) {
2521                    bp.setGids(perm.gids, perm.perUser);
2522                }
2523            }
2524
2525            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2526            final int builtInLibCount = libConfig.size();
2527            for (int i = 0; i < builtInLibCount; i++) {
2528                String name = libConfig.keyAt(i);
2529                String path = libConfig.valueAt(i);
2530                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2531                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2532            }
2533
2534            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2535
2536            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2537            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2538            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2539
2540            // Clean up orphaned packages for which the code path doesn't exist
2541            // and they are an update to a system app - caused by bug/32321269
2542            final int packageSettingCount = mSettings.mPackages.size();
2543            for (int i = packageSettingCount - 1; i >= 0; i--) {
2544                PackageSetting ps = mSettings.mPackages.valueAt(i);
2545                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2546                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2547                    mSettings.mPackages.removeAt(i);
2548                    mSettings.enableSystemPackageLPw(ps.name);
2549                }
2550            }
2551
2552            if (mFirstBoot) {
2553                requestCopyPreoptedFiles();
2554            }
2555
2556            String customResolverActivity = Resources.getSystem().getString(
2557                    R.string.config_customResolverActivity);
2558            if (TextUtils.isEmpty(customResolverActivity)) {
2559                customResolverActivity = null;
2560            } else {
2561                mCustomResolverComponentName = ComponentName.unflattenFromString(
2562                        customResolverActivity);
2563            }
2564
2565            long startTime = SystemClock.uptimeMillis();
2566
2567            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2568                    startTime);
2569
2570            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2571            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2572
2573            if (bootClassPath == null) {
2574                Slog.w(TAG, "No BOOTCLASSPATH found!");
2575            }
2576
2577            if (systemServerClassPath == null) {
2578                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2579            }
2580
2581            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2582
2583            final VersionInfo ver = mSettings.getInternalVersion();
2584            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2585            if (mIsUpgrade) {
2586                logCriticalInfo(Log.INFO,
2587                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2588            }
2589
2590            // when upgrading from pre-M, promote system app permissions from install to runtime
2591            mPromoteSystemApps =
2592                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2593
2594            // When upgrading from pre-N, we need to handle package extraction like first boot,
2595            // as there is no profiling data available.
2596            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2597
2598            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2599
2600            // save off the names of pre-existing system packages prior to scanning; we don't
2601            // want to automatically grant runtime permissions for new system apps
2602            if (mPromoteSystemApps) {
2603                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2604                while (pkgSettingIter.hasNext()) {
2605                    PackageSetting ps = pkgSettingIter.next();
2606                    if (isSystemApp(ps)) {
2607                        mExistingSystemPackages.add(ps.name);
2608                    }
2609                }
2610            }
2611
2612            mCacheDir = preparePackageParserCache(mIsUpgrade);
2613
2614            // Set flag to monitor and not change apk file paths when
2615            // scanning install directories.
2616            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2617
2618            if (mIsUpgrade || mFirstBoot) {
2619                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2620            }
2621
2622            // Collect vendor overlay packages. (Do this before scanning any apps.)
2623            // For security and version matching reason, only consider
2624            // overlay packages if they reside in the right directory.
2625            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2626                    | PackageParser.PARSE_IS_SYSTEM
2627                    | PackageParser.PARSE_IS_SYSTEM_DIR
2628                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2629
2630            mParallelPackageParserCallback.findStaticOverlayPackages();
2631
2632            // Find base frameworks (resource packages without code).
2633            scanDirTracedLI(frameworkDir, mDefParseFlags
2634                    | PackageParser.PARSE_IS_SYSTEM
2635                    | PackageParser.PARSE_IS_SYSTEM_DIR
2636                    | PackageParser.PARSE_IS_PRIVILEGED,
2637                    scanFlags | SCAN_NO_DEX, 0);
2638
2639            // Collected privileged system packages.
2640            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2641            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2642                    | PackageParser.PARSE_IS_SYSTEM
2643                    | PackageParser.PARSE_IS_SYSTEM_DIR
2644                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2645
2646            // Collect ordinary system packages.
2647            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2648            scanDirTracedLI(systemAppDir, mDefParseFlags
2649                    | PackageParser.PARSE_IS_SYSTEM
2650                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2651
2652            // Collect all vendor packages.
2653            File vendorAppDir = new File("/vendor/app");
2654            try {
2655                vendorAppDir = vendorAppDir.getCanonicalFile();
2656            } catch (IOException e) {
2657                // failed to look up canonical path, continue with original one
2658            }
2659            scanDirTracedLI(vendorAppDir, mDefParseFlags
2660                    | PackageParser.PARSE_IS_SYSTEM
2661                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2662
2663            // Collect all OEM packages.
2664            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2665            scanDirTracedLI(oemAppDir, mDefParseFlags
2666                    | PackageParser.PARSE_IS_SYSTEM
2667                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2668
2669            // Prune any system packages that no longer exist.
2670            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2671            // Stub packages must either be replaced with full versions in the /data
2672            // partition or be disabled.
2673            final List<String> stubSystemApps = new ArrayList<>();
2674            if (!mOnlyCore) {
2675                // do this first before mucking with mPackages for the "expecting better" case
2676                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2677                while (pkgIterator.hasNext()) {
2678                    final PackageParser.Package pkg = pkgIterator.next();
2679                    if (pkg.isStub) {
2680                        stubSystemApps.add(pkg.packageName);
2681                    }
2682                }
2683
2684                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2685                while (psit.hasNext()) {
2686                    PackageSetting ps = psit.next();
2687
2688                    /*
2689                     * If this is not a system app, it can't be a
2690                     * disable system app.
2691                     */
2692                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2693                        continue;
2694                    }
2695
2696                    /*
2697                     * If the package is scanned, it's not erased.
2698                     */
2699                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2700                    if (scannedPkg != null) {
2701                        /*
2702                         * If the system app is both scanned and in the
2703                         * disabled packages list, then it must have been
2704                         * added via OTA. Remove it from the currently
2705                         * scanned package so the previously user-installed
2706                         * application can be scanned.
2707                         */
2708                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2709                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2710                                    + ps.name + "; removing system app.  Last known codePath="
2711                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2712                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2713                                    + scannedPkg.mVersionCode);
2714                            removePackageLI(scannedPkg, true);
2715                            mExpectingBetter.put(ps.name, ps.codePath);
2716                        }
2717
2718                        continue;
2719                    }
2720
2721                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2722                        psit.remove();
2723                        logCriticalInfo(Log.WARN, "System package " + ps.name
2724                                + " no longer exists; it's data will be wiped");
2725                        // Actual deletion of code and data will be handled by later
2726                        // reconciliation step
2727                    } else {
2728                        // we still have a disabled system package, but, it still might have
2729                        // been removed. check the code path still exists and check there's
2730                        // still a package. the latter can happen if an OTA keeps the same
2731                        // code path, but, changes the package name.
2732                        final PackageSetting disabledPs =
2733                                mSettings.getDisabledSystemPkgLPr(ps.name);
2734                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2735                                || disabledPs.pkg == null) {
2736                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2737                        }
2738                    }
2739                }
2740            }
2741
2742            //look for any incomplete package installations
2743            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2744            for (int i = 0; i < deletePkgsList.size(); i++) {
2745                // Actual deletion of code and data will be handled by later
2746                // reconciliation step
2747                final String packageName = deletePkgsList.get(i).name;
2748                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2749                synchronized (mPackages) {
2750                    mSettings.removePackageLPw(packageName);
2751                }
2752            }
2753
2754            //delete tmp files
2755            deleteTempPackageFiles();
2756
2757            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2758
2759            // Remove any shared userIDs that have no associated packages
2760            mSettings.pruneSharedUsersLPw();
2761            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2762            final int systemPackagesCount = mPackages.size();
2763            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2764                    + " ms, packageCount: " + systemPackagesCount
2765                    + " , timePerPackage: "
2766                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2767                    + " , cached: " + cachedSystemApps);
2768            if (mIsUpgrade && systemPackagesCount > 0) {
2769                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2770                        ((int) systemScanTime) / systemPackagesCount);
2771            }
2772            if (!mOnlyCore) {
2773                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2774                        SystemClock.uptimeMillis());
2775                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2776
2777                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2778                        | PackageParser.PARSE_FORWARD_LOCK,
2779                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2780
2781                // Remove disable package settings for updated system apps that were
2782                // removed via an OTA. If the update is no longer present, remove the
2783                // app completely. Otherwise, revoke their system privileges.
2784                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2785                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2786                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2787
2788                    final String msg;
2789                    if (deletedPkg == null) {
2790                        // should have found an update, but, we didn't; remove everything
2791                        msg = "Updated system package " + deletedAppName
2792                                + " no longer exists; removing its data";
2793                        // Actual deletion of code and data will be handled by later
2794                        // reconciliation step
2795                    } else {
2796                        // found an update; revoke system privileges
2797                        msg = "Updated system package + " + deletedAppName
2798                                + " no longer exists; revoking system privileges";
2799
2800                        // Don't do anything if a stub is removed from the system image. If
2801                        // we were to remove the uncompressed version from the /data partition,
2802                        // this is where it'd be done.
2803
2804                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2805                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2806                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2807                    }
2808                    logCriticalInfo(Log.WARN, msg);
2809                }
2810
2811                /*
2812                 * Make sure all system apps that we expected to appear on
2813                 * the userdata partition actually showed up. If they never
2814                 * appeared, crawl back and revive the system version.
2815                 */
2816                for (int i = 0; i < mExpectingBetter.size(); i++) {
2817                    final String packageName = mExpectingBetter.keyAt(i);
2818                    if (!mPackages.containsKey(packageName)) {
2819                        final File scanFile = mExpectingBetter.valueAt(i);
2820
2821                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2822                                + " but never showed up; reverting to system");
2823
2824                        int reparseFlags = mDefParseFlags;
2825                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2826                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2827                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2828                                    | PackageParser.PARSE_IS_PRIVILEGED;
2829                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2830                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2831                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2832                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2833                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2834                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2835                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2836                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2837                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2838                        } else {
2839                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2840                            continue;
2841                        }
2842
2843                        mSettings.enableSystemPackageLPw(packageName);
2844
2845                        try {
2846                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2847                        } catch (PackageManagerException e) {
2848                            Slog.e(TAG, "Failed to parse original system package: "
2849                                    + e.getMessage());
2850                        }
2851                    }
2852                }
2853
2854                // Uncompress and install any stubbed system applications.
2855                // This must be done last to ensure all stubs are replaced or disabled.
2856                decompressSystemApplications(stubSystemApps, scanFlags);
2857
2858                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2859                                - cachedSystemApps;
2860
2861                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2862                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2863                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2864                        + " ms, packageCount: " + dataPackagesCount
2865                        + " , timePerPackage: "
2866                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2867                        + " , cached: " + cachedNonSystemApps);
2868                if (mIsUpgrade && dataPackagesCount > 0) {
2869                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2870                            ((int) dataScanTime) / dataPackagesCount);
2871                }
2872            }
2873            mExpectingBetter.clear();
2874
2875            // Resolve the storage manager.
2876            mStorageManagerPackage = getStorageManagerPackageName();
2877
2878            // Resolve protected action filters. Only the setup wizard is allowed to
2879            // have a high priority filter for these actions.
2880            mSetupWizardPackage = getSetupWizardPackageName();
2881            if (mProtectedFilters.size() > 0) {
2882                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2883                    Slog.i(TAG, "No setup wizard;"
2884                        + " All protected intents capped to priority 0");
2885                }
2886                for (ActivityIntentInfo filter : mProtectedFilters) {
2887                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2888                        if (DEBUG_FILTERS) {
2889                            Slog.i(TAG, "Found setup wizard;"
2890                                + " allow priority " + filter.getPriority() + ";"
2891                                + " package: " + filter.activity.info.packageName
2892                                + " activity: " + filter.activity.className
2893                                + " priority: " + filter.getPriority());
2894                        }
2895                        // skip setup wizard; allow it to keep the high priority filter
2896                        continue;
2897                    }
2898                    if (DEBUG_FILTERS) {
2899                        Slog.i(TAG, "Protected action; cap priority to 0;"
2900                                + " package: " + filter.activity.info.packageName
2901                                + " activity: " + filter.activity.className
2902                                + " origPrio: " + filter.getPriority());
2903                    }
2904                    filter.setPriority(0);
2905                }
2906            }
2907            mDeferProtectedFilters = false;
2908            mProtectedFilters.clear();
2909
2910            // Now that we know all of the shared libraries, update all clients to have
2911            // the correct library paths.
2912            updateAllSharedLibrariesLPw(null);
2913
2914            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2915                // NOTE: We ignore potential failures here during a system scan (like
2916                // the rest of the commands above) because there's precious little we
2917                // can do about it. A settings error is reported, though.
2918                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2919            }
2920
2921            // Now that we know all the packages we are keeping,
2922            // read and update their last usage times.
2923            mPackageUsage.read(mPackages);
2924            mCompilerStats.read();
2925
2926            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2927                    SystemClock.uptimeMillis());
2928            Slog.i(TAG, "Time to scan packages: "
2929                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2930                    + " seconds");
2931
2932            // If the platform SDK has changed since the last time we booted,
2933            // we need to re-grant app permission to catch any new ones that
2934            // appear.  This is really a hack, and means that apps can in some
2935            // cases get permissions that the user didn't initially explicitly
2936            // allow...  it would be nice to have some better way to handle
2937            // this situation.
2938            int updateFlags = UPDATE_PERMISSIONS_ALL;
2939            if (ver.sdkVersion != mSdkVersion) {
2940                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2941                        + mSdkVersion + "; regranting permissions for internal storage");
2942                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2943            }
2944            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2945            ver.sdkVersion = mSdkVersion;
2946
2947            // If this is the first boot or an update from pre-M, and it is a normal
2948            // boot, then we need to initialize the default preferred apps across
2949            // all defined users.
2950            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2951                for (UserInfo user : sUserManager.getUsers(true)) {
2952                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2953                    applyFactoryDefaultBrowserLPw(user.id);
2954                    primeDomainVerificationsLPw(user.id);
2955                }
2956            }
2957
2958            // Prepare storage for system user really early during boot,
2959            // since core system apps like SettingsProvider and SystemUI
2960            // can't wait for user to start
2961            final int storageFlags;
2962            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2963                storageFlags = StorageManager.FLAG_STORAGE_DE;
2964            } else {
2965                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2966            }
2967            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2968                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2969                    true /* onlyCoreApps */);
2970            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2971                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2972                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2973                traceLog.traceBegin("AppDataFixup");
2974                try {
2975                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2976                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2977                } catch (InstallerException e) {
2978                    Slog.w(TAG, "Trouble fixing GIDs", e);
2979                }
2980                traceLog.traceEnd();
2981
2982                traceLog.traceBegin("AppDataPrepare");
2983                if (deferPackages == null || deferPackages.isEmpty()) {
2984                    return;
2985                }
2986                int count = 0;
2987                for (String pkgName : deferPackages) {
2988                    PackageParser.Package pkg = null;
2989                    synchronized (mPackages) {
2990                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2991                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2992                            pkg = ps.pkg;
2993                        }
2994                    }
2995                    if (pkg != null) {
2996                        synchronized (mInstallLock) {
2997                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2998                                    true /* maybeMigrateAppData */);
2999                        }
3000                        count++;
3001                    }
3002                }
3003                traceLog.traceEnd();
3004                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3005            }, "prepareAppData");
3006
3007            // If this is first boot after an OTA, and a normal boot, then
3008            // we need to clear code cache directories.
3009            // Note that we do *not* clear the application profiles. These remain valid
3010            // across OTAs and are used to drive profile verification (post OTA) and
3011            // profile compilation (without waiting to collect a fresh set of profiles).
3012            if (mIsUpgrade && !onlyCore) {
3013                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3014                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3015                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3016                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3017                        // No apps are running this early, so no need to freeze
3018                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3019                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3020                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3021                    }
3022                }
3023                ver.fingerprint = Build.FINGERPRINT;
3024            }
3025
3026            checkDefaultBrowser();
3027
3028            // clear only after permissions and other defaults have been updated
3029            mExistingSystemPackages.clear();
3030            mPromoteSystemApps = false;
3031
3032            // All the changes are done during package scanning.
3033            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3034
3035            // can downgrade to reader
3036            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3037            mSettings.writeLPr();
3038            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3039            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3040                    SystemClock.uptimeMillis());
3041
3042            if (!mOnlyCore) {
3043                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3044                mRequiredInstallerPackage = getRequiredInstallerLPr();
3045                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3046                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3047                if (mIntentFilterVerifierComponent != null) {
3048                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3049                            mIntentFilterVerifierComponent);
3050                } else {
3051                    mIntentFilterVerifier = null;
3052                }
3053                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3054                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3055                        SharedLibraryInfo.VERSION_UNDEFINED);
3056                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3057                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3058                        SharedLibraryInfo.VERSION_UNDEFINED);
3059            } else {
3060                mRequiredVerifierPackage = null;
3061                mRequiredInstallerPackage = null;
3062                mRequiredUninstallerPackage = null;
3063                mIntentFilterVerifierComponent = null;
3064                mIntentFilterVerifier = null;
3065                mServicesSystemSharedLibraryPackageName = null;
3066                mSharedSystemSharedLibraryPackageName = null;
3067            }
3068
3069            mInstallerService = new PackageInstallerService(context, this);
3070            final Pair<ComponentName, String> instantAppResolverComponent =
3071                    getInstantAppResolverLPr();
3072            if (instantAppResolverComponent != null) {
3073                if (DEBUG_EPHEMERAL) {
3074                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3075                }
3076                mInstantAppResolverConnection = new EphemeralResolverConnection(
3077                        mContext, instantAppResolverComponent.first,
3078                        instantAppResolverComponent.second);
3079                mInstantAppResolverSettingsComponent =
3080                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3081            } else {
3082                mInstantAppResolverConnection = null;
3083                mInstantAppResolverSettingsComponent = null;
3084            }
3085            updateInstantAppInstallerLocked(null);
3086
3087            // Read and update the usage of dex files.
3088            // Do this at the end of PM init so that all the packages have their
3089            // data directory reconciled.
3090            // At this point we know the code paths of the packages, so we can validate
3091            // the disk file and build the internal cache.
3092            // The usage file is expected to be small so loading and verifying it
3093            // should take a fairly small time compare to the other activities (e.g. package
3094            // scanning).
3095            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3096            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3097            for (int userId : currentUserIds) {
3098                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3099            }
3100            mDexManager.load(userPackages);
3101            if (mIsUpgrade) {
3102                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3103                        (int) (SystemClock.uptimeMillis() - startTime));
3104            }
3105        } // synchronized (mPackages)
3106        } // synchronized (mInstallLock)
3107
3108        // Now after opening every single application zip, make sure they
3109        // are all flushed.  Not really needed, but keeps things nice and
3110        // tidy.
3111        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3112        Runtime.getRuntime().gc();
3113        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3114
3115        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3116        FallbackCategoryProvider.loadFallbacks();
3117        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3118
3119        // The initial scanning above does many calls into installd while
3120        // holding the mPackages lock, but we're mostly interested in yelling
3121        // once we have a booted system.
3122        mInstaller.setWarnIfHeld(mPackages);
3123
3124        // Expose private service for system components to use.
3125        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3126        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3127    }
3128
3129    /**
3130     * Uncompress and install stub applications.
3131     * <p>In order to save space on the system partition, some applications are shipped in a
3132     * compressed form. In addition the compressed bits for the full application, the
3133     * system image contains a tiny stub comprised of only the Android manifest.
3134     * <p>During the first boot, attempt to uncompress and install the full application. If
3135     * the application can't be installed for any reason, disable the stub and prevent
3136     * uncompressing the full application during future boots.
3137     * <p>In order to forcefully attempt an installation of a full application, go to app
3138     * settings and enable the application.
3139     */
3140    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3141        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3142            final String pkgName = stubSystemApps.get(i);
3143            // skip if the system package is already disabled
3144            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3145                stubSystemApps.remove(i);
3146                continue;
3147            }
3148            // skip if the package isn't installed (?!); this should never happen
3149            final PackageParser.Package pkg = mPackages.get(pkgName);
3150            if (pkg == null) {
3151                stubSystemApps.remove(i);
3152                continue;
3153            }
3154            // skip if the package has been disabled by the user
3155            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3156            if (ps != null) {
3157                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3158                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3159                    stubSystemApps.remove(i);
3160                    continue;
3161                }
3162            }
3163
3164            if (DEBUG_COMPRESSION) {
3165                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3166            }
3167
3168            // uncompress the binary to its eventual destination on /data
3169            final File scanFile = decompressPackage(pkg);
3170            if (scanFile == null) {
3171                continue;
3172            }
3173
3174            // install the package to replace the stub on /system
3175            try {
3176                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3177                removePackageLI(pkg, true /*chatty*/);
3178                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3179                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3180                        UserHandle.USER_SYSTEM, "android");
3181                stubSystemApps.remove(i);
3182                continue;
3183            } catch (PackageManagerException e) {
3184                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3185            }
3186
3187            // any failed attempt to install the package will be cleaned up later
3188        }
3189
3190        // disable any stub still left; these failed to install the full application
3191        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3192            final String pkgName = stubSystemApps.get(i);
3193            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3194            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3195                    UserHandle.USER_SYSTEM, "android");
3196            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3197        }
3198    }
3199
3200    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3201        if (DEBUG_COMPRESSION) {
3202            Slog.i(TAG, "Decompress file"
3203                    + "; src: " + srcFile.getAbsolutePath()
3204                    + ", dst: " + dstFile.getAbsolutePath());
3205        }
3206        try (
3207                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3208                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3209        ) {
3210            Streams.copy(fileIn, fileOut);
3211            Os.chmod(dstFile.getAbsolutePath(), 0644);
3212            return PackageManager.INSTALL_SUCCEEDED;
3213        } catch (IOException e) {
3214            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3215                    + "; src: " + srcFile.getAbsolutePath()
3216                    + ", dst: " + dstFile.getAbsolutePath());
3217        }
3218        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3219    }
3220
3221    private File[] getCompressedFiles(String codePath) {
3222        final File stubCodePath = new File(codePath);
3223        final String stubName = stubCodePath.getName();
3224
3225        // The layout of a compressed package on a given partition is as follows :
3226        //
3227        // Compressed artifacts:
3228        //
3229        // /partition/ModuleName/foo.gz
3230        // /partation/ModuleName/bar.gz
3231        //
3232        // Stub artifact:
3233        //
3234        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3235        //
3236        // In other words, stub is on the same partition as the compressed artifacts
3237        // and in a directory that's suffixed with "-Stub".
3238        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3239        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3240            return null;
3241        }
3242
3243        final File stubParentDir = stubCodePath.getParentFile();
3244        if (stubParentDir == null) {
3245            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3246            return null;
3247        }
3248
3249        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3250        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3251            @Override
3252            public boolean accept(File dir, String name) {
3253                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3254            }
3255        });
3256
3257        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3258            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3259        }
3260
3261        return files;
3262    }
3263
3264    private boolean compressedFileExists(String codePath) {
3265        final File[] compressedFiles = getCompressedFiles(codePath);
3266        return compressedFiles != null && compressedFiles.length > 0;
3267    }
3268
3269    /**
3270     * Decompresses the given package on the system image onto
3271     * the /data partition.
3272     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3273     */
3274    private File decompressPackage(PackageParser.Package pkg) {
3275        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3276        if (compressedFiles == null || compressedFiles.length == 0) {
3277            if (DEBUG_COMPRESSION) {
3278                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3279            }
3280            return null;
3281        }
3282        final File dstCodePath =
3283                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3284        int ret = PackageManager.INSTALL_SUCCEEDED;
3285        try {
3286            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3287            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3288            for (File srcFile : compressedFiles) {
3289                final String srcFileName = srcFile.getName();
3290                final String dstFileName = srcFileName.substring(
3291                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3292                final File dstFile = new File(dstCodePath, dstFileName);
3293                ret = decompressFile(srcFile, dstFile);
3294                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3295                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3296                            + "; pkg: " + pkg.packageName
3297                            + ", file: " + dstFileName);
3298                    break;
3299                }
3300            }
3301        } catch (ErrnoException e) {
3302            logCriticalInfo(Log.ERROR, "Failed to decompress"
3303                    + "; pkg: " + pkg.packageName
3304                    + ", err: " + e.errno);
3305        }
3306        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3307            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3308            NativeLibraryHelper.Handle handle = null;
3309            try {
3310                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3311                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3312                        null /*abiOverride*/);
3313            } catch (IOException e) {
3314                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3315                        + "; pkg: " + pkg.packageName);
3316                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3317            } finally {
3318                IoUtils.closeQuietly(handle);
3319            }
3320        }
3321        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3322            if (dstCodePath == null || !dstCodePath.exists()) {
3323                return null;
3324            }
3325            removeCodePathLI(dstCodePath);
3326            return null;
3327        }
3328
3329        return dstCodePath;
3330    }
3331
3332    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3333        // we're only interested in updating the installer appliction when 1) it's not
3334        // already set or 2) the modified package is the installer
3335        if (mInstantAppInstallerActivity != null
3336                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3337                        .equals(modifiedPackage)) {
3338            return;
3339        }
3340        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3341    }
3342
3343    private static File preparePackageParserCache(boolean isUpgrade) {
3344        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3345            return null;
3346        }
3347
3348        // Disable package parsing on eng builds to allow for faster incremental development.
3349        if (Build.IS_ENG) {
3350            return null;
3351        }
3352
3353        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3354            Slog.i(TAG, "Disabling package parser cache due to system property.");
3355            return null;
3356        }
3357
3358        // The base directory for the package parser cache lives under /data/system/.
3359        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3360                "package_cache");
3361        if (cacheBaseDir == null) {
3362            return null;
3363        }
3364
3365        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3366        // This also serves to "GC" unused entries when the package cache version changes (which
3367        // can only happen during upgrades).
3368        if (isUpgrade) {
3369            FileUtils.deleteContents(cacheBaseDir);
3370        }
3371
3372
3373        // Return the versioned package cache directory. This is something like
3374        // "/data/system/package_cache/1"
3375        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3376
3377        // The following is a workaround to aid development on non-numbered userdebug
3378        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3379        // the system partition is newer.
3380        //
3381        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3382        // that starts with "eng." to signify that this is an engineering build and not
3383        // destined for release.
3384        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3385            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3386
3387            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3388            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3389            // in general and should not be used for production changes. In this specific case,
3390            // we know that they will work.
3391            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3392            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3393                FileUtils.deleteContents(cacheBaseDir);
3394                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3395            }
3396        }
3397
3398        return cacheDir;
3399    }
3400
3401    @Override
3402    public boolean isFirstBoot() {
3403        // allow instant applications
3404        return mFirstBoot;
3405    }
3406
3407    @Override
3408    public boolean isOnlyCoreApps() {
3409        // allow instant applications
3410        return mOnlyCore;
3411    }
3412
3413    @Override
3414    public boolean isUpgrade() {
3415        // allow instant applications
3416        return mIsUpgrade;
3417    }
3418
3419    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3420        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3421
3422        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3423                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3424                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3425        if (matches.size() == 1) {
3426            return matches.get(0).getComponentInfo().packageName;
3427        } else if (matches.size() == 0) {
3428            Log.e(TAG, "There should probably be a verifier, but, none were found");
3429            return null;
3430        }
3431        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3432    }
3433
3434    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3435        synchronized (mPackages) {
3436            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3437            if (libraryEntry == null) {
3438                throw new IllegalStateException("Missing required shared library:" + name);
3439            }
3440            return libraryEntry.apk;
3441        }
3442    }
3443
3444    private @NonNull String getRequiredInstallerLPr() {
3445        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3446        intent.addCategory(Intent.CATEGORY_DEFAULT);
3447        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3448
3449        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3450                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3451                UserHandle.USER_SYSTEM);
3452        if (matches.size() == 1) {
3453            ResolveInfo resolveInfo = matches.get(0);
3454            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3455                throw new RuntimeException("The installer must be a privileged app");
3456            }
3457            return matches.get(0).getComponentInfo().packageName;
3458        } else {
3459            throw new RuntimeException("There must be exactly one installer; found " + matches);
3460        }
3461    }
3462
3463    private @NonNull String getRequiredUninstallerLPr() {
3464        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3465        intent.addCategory(Intent.CATEGORY_DEFAULT);
3466        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3467
3468        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3469                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3470                UserHandle.USER_SYSTEM);
3471        if (resolveInfo == null ||
3472                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3473            throw new RuntimeException("There must be exactly one uninstaller; found "
3474                    + resolveInfo);
3475        }
3476        return resolveInfo.getComponentInfo().packageName;
3477    }
3478
3479    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3480        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3481
3482        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3483                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3484                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3485        ResolveInfo best = null;
3486        final int N = matches.size();
3487        for (int i = 0; i < N; i++) {
3488            final ResolveInfo cur = matches.get(i);
3489            final String packageName = cur.getComponentInfo().packageName;
3490            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3491                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3492                continue;
3493            }
3494
3495            if (best == null || cur.priority > best.priority) {
3496                best = cur;
3497            }
3498        }
3499
3500        if (best != null) {
3501            return best.getComponentInfo().getComponentName();
3502        }
3503        Slog.w(TAG, "Intent filter verifier not found");
3504        return null;
3505    }
3506
3507    @Override
3508    public @Nullable ComponentName getInstantAppResolverComponent() {
3509        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3510            return null;
3511        }
3512        synchronized (mPackages) {
3513            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3514            if (instantAppResolver == null) {
3515                return null;
3516            }
3517            return instantAppResolver.first;
3518        }
3519    }
3520
3521    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3522        final String[] packageArray =
3523                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3524        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3525            if (DEBUG_EPHEMERAL) {
3526                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3527            }
3528            return null;
3529        }
3530
3531        final int callingUid = Binder.getCallingUid();
3532        final int resolveFlags =
3533                MATCH_DIRECT_BOOT_AWARE
3534                | MATCH_DIRECT_BOOT_UNAWARE
3535                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3536        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3537        final Intent resolverIntent = new Intent(actionName);
3538        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3539                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3540        // temporarily look for the old action
3541        if (resolvers.size() == 0) {
3542            if (DEBUG_EPHEMERAL) {
3543                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3544            }
3545            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3546            resolverIntent.setAction(actionName);
3547            resolvers = queryIntentServicesInternal(resolverIntent, null,
3548                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3549        }
3550        final int N = resolvers.size();
3551        if (N == 0) {
3552            if (DEBUG_EPHEMERAL) {
3553                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3554            }
3555            return null;
3556        }
3557
3558        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3559        for (int i = 0; i < N; i++) {
3560            final ResolveInfo info = resolvers.get(i);
3561
3562            if (info.serviceInfo == null) {
3563                continue;
3564            }
3565
3566            final String packageName = info.serviceInfo.packageName;
3567            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3568                if (DEBUG_EPHEMERAL) {
3569                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3570                            + " pkg: " + packageName + ", info:" + info);
3571                }
3572                continue;
3573            }
3574
3575            if (DEBUG_EPHEMERAL) {
3576                Slog.v(TAG, "Ephemeral resolver found;"
3577                        + " pkg: " + packageName + ", info:" + info);
3578            }
3579            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3580        }
3581        if (DEBUG_EPHEMERAL) {
3582            Slog.v(TAG, "Ephemeral resolver NOT found");
3583        }
3584        return null;
3585    }
3586
3587    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3588        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3589        intent.addCategory(Intent.CATEGORY_DEFAULT);
3590        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3591
3592        final int resolveFlags =
3593                MATCH_DIRECT_BOOT_AWARE
3594                | MATCH_DIRECT_BOOT_UNAWARE
3595                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3596        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3597                resolveFlags, UserHandle.USER_SYSTEM);
3598        // temporarily look for the old action
3599        if (matches.isEmpty()) {
3600            if (DEBUG_EPHEMERAL) {
3601                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3602            }
3603            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3604            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3605                    resolveFlags, UserHandle.USER_SYSTEM);
3606        }
3607        Iterator<ResolveInfo> iter = matches.iterator();
3608        while (iter.hasNext()) {
3609            final ResolveInfo rInfo = iter.next();
3610            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3611            if (ps != null) {
3612                final PermissionsState permissionsState = ps.getPermissionsState();
3613                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3614                    continue;
3615                }
3616            }
3617            iter.remove();
3618        }
3619        if (matches.size() == 0) {
3620            return null;
3621        } else if (matches.size() == 1) {
3622            return (ActivityInfo) matches.get(0).getComponentInfo();
3623        } else {
3624            throw new RuntimeException(
3625                    "There must be at most one ephemeral installer; found " + matches);
3626        }
3627    }
3628
3629    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3630            @NonNull ComponentName resolver) {
3631        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3632                .addCategory(Intent.CATEGORY_DEFAULT)
3633                .setPackage(resolver.getPackageName());
3634        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3635        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3636                UserHandle.USER_SYSTEM);
3637        // temporarily look for the old action
3638        if (matches.isEmpty()) {
3639            if (DEBUG_EPHEMERAL) {
3640                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3641            }
3642            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3643            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3644                    UserHandle.USER_SYSTEM);
3645        }
3646        if (matches.isEmpty()) {
3647            return null;
3648        }
3649        return matches.get(0).getComponentInfo().getComponentName();
3650    }
3651
3652    private void primeDomainVerificationsLPw(int userId) {
3653        if (DEBUG_DOMAIN_VERIFICATION) {
3654            Slog.d(TAG, "Priming domain verifications in user " + userId);
3655        }
3656
3657        SystemConfig systemConfig = SystemConfig.getInstance();
3658        ArraySet<String> packages = systemConfig.getLinkedApps();
3659
3660        for (String packageName : packages) {
3661            PackageParser.Package pkg = mPackages.get(packageName);
3662            if (pkg != null) {
3663                if (!pkg.isSystemApp()) {
3664                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3665                    continue;
3666                }
3667
3668                ArraySet<String> domains = null;
3669                for (PackageParser.Activity a : pkg.activities) {
3670                    for (ActivityIntentInfo filter : a.intents) {
3671                        if (hasValidDomains(filter)) {
3672                            if (domains == null) {
3673                                domains = new ArraySet<String>();
3674                            }
3675                            domains.addAll(filter.getHostsList());
3676                        }
3677                    }
3678                }
3679
3680                if (domains != null && domains.size() > 0) {
3681                    if (DEBUG_DOMAIN_VERIFICATION) {
3682                        Slog.v(TAG, "      + " + packageName);
3683                    }
3684                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3685                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3686                    // and then 'always' in the per-user state actually used for intent resolution.
3687                    final IntentFilterVerificationInfo ivi;
3688                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3689                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3690                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3691                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3692                } else {
3693                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3694                            + "' does not handle web links");
3695                }
3696            } else {
3697                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3698            }
3699        }
3700
3701        scheduleWritePackageRestrictionsLocked(userId);
3702        scheduleWriteSettingsLocked();
3703    }
3704
3705    private void applyFactoryDefaultBrowserLPw(int userId) {
3706        // The default browser app's package name is stored in a string resource,
3707        // with a product-specific overlay used for vendor customization.
3708        String browserPkg = mContext.getResources().getString(
3709                com.android.internal.R.string.default_browser);
3710        if (!TextUtils.isEmpty(browserPkg)) {
3711            // non-empty string => required to be a known package
3712            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3713            if (ps == null) {
3714                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3715                browserPkg = null;
3716            } else {
3717                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3718            }
3719        }
3720
3721        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3722        // default.  If there's more than one, just leave everything alone.
3723        if (browserPkg == null) {
3724            calculateDefaultBrowserLPw(userId);
3725        }
3726    }
3727
3728    private void calculateDefaultBrowserLPw(int userId) {
3729        List<String> allBrowsers = resolveAllBrowserApps(userId);
3730        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3731        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3732    }
3733
3734    private List<String> resolveAllBrowserApps(int userId) {
3735        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3736        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3737                PackageManager.MATCH_ALL, userId);
3738
3739        final int count = list.size();
3740        List<String> result = new ArrayList<String>(count);
3741        for (int i=0; i<count; i++) {
3742            ResolveInfo info = list.get(i);
3743            if (info.activityInfo == null
3744                    || !info.handleAllWebDataURI
3745                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3746                    || result.contains(info.activityInfo.packageName)) {
3747                continue;
3748            }
3749            result.add(info.activityInfo.packageName);
3750        }
3751
3752        return result;
3753    }
3754
3755    private boolean packageIsBrowser(String packageName, int userId) {
3756        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3757                PackageManager.MATCH_ALL, userId);
3758        final int N = list.size();
3759        for (int i = 0; i < N; i++) {
3760            ResolveInfo info = list.get(i);
3761            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3762                return true;
3763            }
3764        }
3765        return false;
3766    }
3767
3768    private void checkDefaultBrowser() {
3769        final int myUserId = UserHandle.myUserId();
3770        final String packageName = getDefaultBrowserPackageName(myUserId);
3771        if (packageName != null) {
3772            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3773            if (info == null) {
3774                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3775                synchronized (mPackages) {
3776                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3777                }
3778            }
3779        }
3780    }
3781
3782    @Override
3783    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3784            throws RemoteException {
3785        try {
3786            return super.onTransact(code, data, reply, flags);
3787        } catch (RuntimeException e) {
3788            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3789                Slog.wtf(TAG, "Package Manager Crash", e);
3790            }
3791            throw e;
3792        }
3793    }
3794
3795    static int[] appendInts(int[] cur, int[] add) {
3796        if (add == null) return cur;
3797        if (cur == null) return add;
3798        final int N = add.length;
3799        for (int i=0; i<N; i++) {
3800            cur = appendInt(cur, add[i]);
3801        }
3802        return cur;
3803    }
3804
3805    /**
3806     * Returns whether or not a full application can see an instant application.
3807     * <p>
3808     * Currently, there are three cases in which this can occur:
3809     * <ol>
3810     * <li>The calling application is a "special" process. The special
3811     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3812     *     and {@code 0}</li>
3813     * <li>The calling application has the permission
3814     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3815     * <li>The calling application is the default launcher on the
3816     *     system partition.</li>
3817     * </ol>
3818     */
3819    private boolean canViewInstantApps(int callingUid, int userId) {
3820        if (callingUid == Process.SYSTEM_UID
3821                || callingUid == Process.SHELL_UID
3822                || callingUid == Process.ROOT_UID) {
3823            return true;
3824        }
3825        if (mContext.checkCallingOrSelfPermission(
3826                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3827            return true;
3828        }
3829        if (mContext.checkCallingOrSelfPermission(
3830                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3831            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3832            if (homeComponent != null
3833                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3834                return true;
3835            }
3836        }
3837        return false;
3838    }
3839
3840    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3841        if (!sUserManager.exists(userId)) return null;
3842        if (ps == null) {
3843            return null;
3844        }
3845        PackageParser.Package p = ps.pkg;
3846        if (p == null) {
3847            return null;
3848        }
3849        final int callingUid = Binder.getCallingUid();
3850        // Filter out ephemeral app metadata:
3851        //   * The system/shell/root can see metadata for any app
3852        //   * An installed app can see metadata for 1) other installed apps
3853        //     and 2) ephemeral apps that have explicitly interacted with it
3854        //   * Ephemeral apps can only see their own data and exposed installed apps
3855        //   * Holding a signature permission allows seeing instant apps
3856        if (filterAppAccessLPr(ps, callingUid, userId)) {
3857            return null;
3858        }
3859
3860        final PermissionsState permissionsState = ps.getPermissionsState();
3861
3862        // Compute GIDs only if requested
3863        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3864                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3865        // Compute granted permissions only if package has requested permissions
3866        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3867                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3868        final PackageUserState state = ps.readUserState(userId);
3869
3870        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3871                && ps.isSystem()) {
3872            flags |= MATCH_ANY_USER;
3873        }
3874
3875        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3876                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3877
3878        if (packageInfo == null) {
3879            return null;
3880        }
3881
3882        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3883                resolveExternalPackageNameLPr(p);
3884
3885        return packageInfo;
3886    }
3887
3888    @Override
3889    public void checkPackageStartable(String packageName, int userId) {
3890        final int callingUid = Binder.getCallingUid();
3891        if (getInstantAppPackageName(callingUid) != null) {
3892            throw new SecurityException("Instant applications don't have access to this method");
3893        }
3894        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3895        synchronized (mPackages) {
3896            final PackageSetting ps = mSettings.mPackages.get(packageName);
3897            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3898                throw new SecurityException("Package " + packageName + " was not found!");
3899            }
3900
3901            if (!ps.getInstalled(userId)) {
3902                throw new SecurityException(
3903                        "Package " + packageName + " was not installed for user " + userId + "!");
3904            }
3905
3906            if (mSafeMode && !ps.isSystem()) {
3907                throw new SecurityException("Package " + packageName + " not a system app!");
3908            }
3909
3910            if (mFrozenPackages.contains(packageName)) {
3911                throw new SecurityException("Package " + packageName + " is currently frozen!");
3912            }
3913
3914            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3915                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3916            }
3917        }
3918    }
3919
3920    @Override
3921    public boolean isPackageAvailable(String packageName, int userId) {
3922        if (!sUserManager.exists(userId)) return false;
3923        final int callingUid = Binder.getCallingUid();
3924        enforceCrossUserPermission(callingUid, userId,
3925                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3926        synchronized (mPackages) {
3927            PackageParser.Package p = mPackages.get(packageName);
3928            if (p != null) {
3929                final PackageSetting ps = (PackageSetting) p.mExtras;
3930                if (filterAppAccessLPr(ps, callingUid, userId)) {
3931                    return false;
3932                }
3933                if (ps != null) {
3934                    final PackageUserState state = ps.readUserState(userId);
3935                    if (state != null) {
3936                        return PackageParser.isAvailable(state);
3937                    }
3938                }
3939            }
3940        }
3941        return false;
3942    }
3943
3944    @Override
3945    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3946        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3947                flags, Binder.getCallingUid(), userId);
3948    }
3949
3950    @Override
3951    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3952            int flags, int userId) {
3953        return getPackageInfoInternal(versionedPackage.getPackageName(),
3954                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3955    }
3956
3957    /**
3958     * Important: The provided filterCallingUid is used exclusively to filter out packages
3959     * that can be seen based on user state. It's typically the original caller uid prior
3960     * to clearing. Because it can only be provided by trusted code, it's value can be
3961     * trusted and will be used as-is; unlike userId which will be validated by this method.
3962     */
3963    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3964            int flags, int filterCallingUid, int userId) {
3965        if (!sUserManager.exists(userId)) return null;
3966        flags = updateFlagsForPackage(flags, userId, packageName);
3967        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3968                false /* requireFullPermission */, false /* checkShell */, "get package info");
3969
3970        // reader
3971        synchronized (mPackages) {
3972            // Normalize package name to handle renamed packages and static libs
3973            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3974
3975            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3976            if (matchFactoryOnly) {
3977                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3978                if (ps != null) {
3979                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3980                        return null;
3981                    }
3982                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3983                        return null;
3984                    }
3985                    return generatePackageInfo(ps, flags, userId);
3986                }
3987            }
3988
3989            PackageParser.Package p = mPackages.get(packageName);
3990            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3991                return null;
3992            }
3993            if (DEBUG_PACKAGE_INFO)
3994                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3995            if (p != null) {
3996                final PackageSetting ps = (PackageSetting) p.mExtras;
3997                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3998                    return null;
3999                }
4000                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4001                    return null;
4002                }
4003                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4004            }
4005            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4006                final PackageSetting ps = mSettings.mPackages.get(packageName);
4007                if (ps == null) return null;
4008                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4009                    return null;
4010                }
4011                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4012                    return null;
4013                }
4014                return generatePackageInfo(ps, flags, userId);
4015            }
4016        }
4017        return null;
4018    }
4019
4020    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4021        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4022            return true;
4023        }
4024        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4025            return true;
4026        }
4027        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4028            return true;
4029        }
4030        return false;
4031    }
4032
4033    private boolean isComponentVisibleToInstantApp(
4034            @Nullable ComponentName component, @ComponentType int type) {
4035        if (type == TYPE_ACTIVITY) {
4036            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4037            return activity != null
4038                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4039                    : false;
4040        } else if (type == TYPE_RECEIVER) {
4041            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4042            return activity != null
4043                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4044                    : false;
4045        } else if (type == TYPE_SERVICE) {
4046            final PackageParser.Service service = mServices.mServices.get(component);
4047            return service != null
4048                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4049                    : false;
4050        } else if (type == TYPE_PROVIDER) {
4051            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4052            return provider != null
4053                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4054                    : false;
4055        } else if (type == TYPE_UNKNOWN) {
4056            return isComponentVisibleToInstantApp(component);
4057        }
4058        return false;
4059    }
4060
4061    /**
4062     * Returns whether or not access to the application should be filtered.
4063     * <p>
4064     * Access may be limited based upon whether the calling or target applications
4065     * are instant applications.
4066     *
4067     * @see #canAccessInstantApps(int)
4068     */
4069    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4070            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4071        // if we're in an isolated process, get the real calling UID
4072        if (Process.isIsolated(callingUid)) {
4073            callingUid = mIsolatedOwners.get(callingUid);
4074        }
4075        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4076        final boolean callerIsInstantApp = instantAppPkgName != null;
4077        if (ps == null) {
4078            if (callerIsInstantApp) {
4079                // pretend the application exists, but, needs to be filtered
4080                return true;
4081            }
4082            return false;
4083        }
4084        // if the target and caller are the same application, don't filter
4085        if (isCallerSameApp(ps.name, callingUid)) {
4086            return false;
4087        }
4088        if (callerIsInstantApp) {
4089            // request for a specific component; if it hasn't been explicitly exposed, filter
4090            if (component != null) {
4091                return !isComponentVisibleToInstantApp(component, componentType);
4092            }
4093            // request for application; if no components have been explicitly exposed, filter
4094            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4095        }
4096        if (ps.getInstantApp(userId)) {
4097            // caller can see all components of all instant applications, don't filter
4098            if (canViewInstantApps(callingUid, userId)) {
4099                return false;
4100            }
4101            // request for a specific instant application component, filter
4102            if (component != null) {
4103                return true;
4104            }
4105            // request for an instant application; if the caller hasn't been granted access, filter
4106            return !mInstantAppRegistry.isInstantAccessGranted(
4107                    userId, UserHandle.getAppId(callingUid), ps.appId);
4108        }
4109        return false;
4110    }
4111
4112    /**
4113     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4114     */
4115    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4116        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4117    }
4118
4119    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4120            int flags) {
4121        // Callers can access only the libs they depend on, otherwise they need to explicitly
4122        // ask for the shared libraries given the caller is allowed to access all static libs.
4123        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4124            // System/shell/root get to see all static libs
4125            final int appId = UserHandle.getAppId(uid);
4126            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4127                    || appId == Process.ROOT_UID) {
4128                return false;
4129            }
4130        }
4131
4132        // No package means no static lib as it is always on internal storage
4133        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4134            return false;
4135        }
4136
4137        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4138                ps.pkg.staticSharedLibVersion);
4139        if (libEntry == null) {
4140            return false;
4141        }
4142
4143        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4144        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4145        if (uidPackageNames == null) {
4146            return true;
4147        }
4148
4149        for (String uidPackageName : uidPackageNames) {
4150            if (ps.name.equals(uidPackageName)) {
4151                return false;
4152            }
4153            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4154            if (uidPs != null) {
4155                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4156                        libEntry.info.getName());
4157                if (index < 0) {
4158                    continue;
4159                }
4160                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4161                    return false;
4162                }
4163            }
4164        }
4165        return true;
4166    }
4167
4168    @Override
4169    public String[] currentToCanonicalPackageNames(String[] names) {
4170        final int callingUid = Binder.getCallingUid();
4171        if (getInstantAppPackageName(callingUid) != null) {
4172            return names;
4173        }
4174        final String[] out = new String[names.length];
4175        // reader
4176        synchronized (mPackages) {
4177            final int callingUserId = UserHandle.getUserId(callingUid);
4178            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4179            for (int i=names.length-1; i>=0; i--) {
4180                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4181                boolean translateName = false;
4182                if (ps != null && ps.realName != null) {
4183                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4184                    translateName = !targetIsInstantApp
4185                            || canViewInstantApps
4186                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4187                                    UserHandle.getAppId(callingUid), ps.appId);
4188                }
4189                out[i] = translateName ? ps.realName : names[i];
4190            }
4191        }
4192        return out;
4193    }
4194
4195    @Override
4196    public String[] canonicalToCurrentPackageNames(String[] names) {
4197        final int callingUid = Binder.getCallingUid();
4198        if (getInstantAppPackageName(callingUid) != null) {
4199            return names;
4200        }
4201        final String[] out = new String[names.length];
4202        // reader
4203        synchronized (mPackages) {
4204            final int callingUserId = UserHandle.getUserId(callingUid);
4205            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4206            for (int i=names.length-1; i>=0; i--) {
4207                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4208                boolean translateName = false;
4209                if (cur != null) {
4210                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4211                    final boolean targetIsInstantApp =
4212                            ps != null && ps.getInstantApp(callingUserId);
4213                    translateName = !targetIsInstantApp
4214                            || canViewInstantApps
4215                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4216                                    UserHandle.getAppId(callingUid), ps.appId);
4217                }
4218                out[i] = translateName ? cur : names[i];
4219            }
4220        }
4221        return out;
4222    }
4223
4224    @Override
4225    public int getPackageUid(String packageName, int flags, int userId) {
4226        if (!sUserManager.exists(userId)) return -1;
4227        final int callingUid = Binder.getCallingUid();
4228        flags = updateFlagsForPackage(flags, userId, packageName);
4229        enforceCrossUserPermission(callingUid, userId,
4230                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4231
4232        // reader
4233        synchronized (mPackages) {
4234            final PackageParser.Package p = mPackages.get(packageName);
4235            if (p != null && p.isMatch(flags)) {
4236                PackageSetting ps = (PackageSetting) p.mExtras;
4237                if (filterAppAccessLPr(ps, callingUid, userId)) {
4238                    return -1;
4239                }
4240                return UserHandle.getUid(userId, p.applicationInfo.uid);
4241            }
4242            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4243                final PackageSetting ps = mSettings.mPackages.get(packageName);
4244                if (ps != null && ps.isMatch(flags)
4245                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4246                    return UserHandle.getUid(userId, ps.appId);
4247                }
4248            }
4249        }
4250
4251        return -1;
4252    }
4253
4254    @Override
4255    public int[] getPackageGids(String packageName, int flags, int userId) {
4256        if (!sUserManager.exists(userId)) return null;
4257        final int callingUid = Binder.getCallingUid();
4258        flags = updateFlagsForPackage(flags, userId, packageName);
4259        enforceCrossUserPermission(callingUid, userId,
4260                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4261
4262        // reader
4263        synchronized (mPackages) {
4264            final PackageParser.Package p = mPackages.get(packageName);
4265            if (p != null && p.isMatch(flags)) {
4266                PackageSetting ps = (PackageSetting) p.mExtras;
4267                if (filterAppAccessLPr(ps, callingUid, userId)) {
4268                    return null;
4269                }
4270                // TODO: Shouldn't this be checking for package installed state for userId and
4271                // return null?
4272                return ps.getPermissionsState().computeGids(userId);
4273            }
4274            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4275                final PackageSetting ps = mSettings.mPackages.get(packageName);
4276                if (ps != null && ps.isMatch(flags)
4277                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4278                    return ps.getPermissionsState().computeGids(userId);
4279                }
4280            }
4281        }
4282
4283        return null;
4284    }
4285
4286    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4287        if (bp.perm != null) {
4288            return PackageParser.generatePermissionInfo(bp.perm, flags);
4289        }
4290        PermissionInfo pi = new PermissionInfo();
4291        pi.name = bp.name;
4292        pi.packageName = bp.sourcePackage;
4293        pi.nonLocalizedLabel = bp.name;
4294        pi.protectionLevel = bp.protectionLevel;
4295        return pi;
4296    }
4297
4298    @Override
4299    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4300        final int callingUid = Binder.getCallingUid();
4301        if (getInstantAppPackageName(callingUid) != null) {
4302            return null;
4303        }
4304        // reader
4305        synchronized (mPackages) {
4306            final BasePermission p = mSettings.mPermissions.get(name);
4307            if (p == null) {
4308                return null;
4309            }
4310            // If the caller is an app that targets pre 26 SDK drop protection flags.
4311            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4312            if (permissionInfo != null) {
4313                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4314                        permissionInfo.protectionLevel, packageName, callingUid);
4315                if (permissionInfo.protectionLevel != protectionLevel) {
4316                    // If we return different protection level, don't use the cached info
4317                    if (p.perm != null && p.perm.info == permissionInfo) {
4318                        permissionInfo = new PermissionInfo(permissionInfo);
4319                    }
4320                    permissionInfo.protectionLevel = protectionLevel;
4321                }
4322            }
4323            return permissionInfo;
4324        }
4325    }
4326
4327    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4328            String packageName, int uid) {
4329        // Signature permission flags area always reported
4330        final int protectionLevelMasked = protectionLevel
4331                & (PermissionInfo.PROTECTION_NORMAL
4332                | PermissionInfo.PROTECTION_DANGEROUS
4333                | PermissionInfo.PROTECTION_SIGNATURE);
4334        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4335            return protectionLevel;
4336        }
4337
4338        // System sees all flags.
4339        final int appId = UserHandle.getAppId(uid);
4340        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4341                || appId == Process.SHELL_UID) {
4342            return protectionLevel;
4343        }
4344
4345        // Normalize package name to handle renamed packages and static libs
4346        packageName = resolveInternalPackageNameLPr(packageName,
4347                PackageManager.VERSION_CODE_HIGHEST);
4348
4349        // Apps that target O see flags for all protection levels.
4350        final PackageSetting ps = mSettings.mPackages.get(packageName);
4351        if (ps == null) {
4352            return protectionLevel;
4353        }
4354        if (ps.appId != appId) {
4355            return protectionLevel;
4356        }
4357
4358        final PackageParser.Package pkg = mPackages.get(packageName);
4359        if (pkg == null) {
4360            return protectionLevel;
4361        }
4362        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4363            return protectionLevelMasked;
4364        }
4365
4366        return protectionLevel;
4367    }
4368
4369    @Override
4370    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4371            int flags) {
4372        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4373            return null;
4374        }
4375        // reader
4376        synchronized (mPackages) {
4377            if (group != null && !mPermissionGroups.containsKey(group)) {
4378                // This is thrown as NameNotFoundException
4379                return null;
4380            }
4381
4382            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4383            for (BasePermission p : mSettings.mPermissions.values()) {
4384                if (group == null) {
4385                    if (p.perm == null || p.perm.info.group == null) {
4386                        out.add(generatePermissionInfo(p, flags));
4387                    }
4388                } else {
4389                    if (p.perm != null && group.equals(p.perm.info.group)) {
4390                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4391                    }
4392                }
4393            }
4394            return new ParceledListSlice<>(out);
4395        }
4396    }
4397
4398    @Override
4399    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4400        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4401            return null;
4402        }
4403        // reader
4404        synchronized (mPackages) {
4405            return PackageParser.generatePermissionGroupInfo(
4406                    mPermissionGroups.get(name), flags);
4407        }
4408    }
4409
4410    @Override
4411    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4412        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4413            return ParceledListSlice.emptyList();
4414        }
4415        // reader
4416        synchronized (mPackages) {
4417            final int N = mPermissionGroups.size();
4418            ArrayList<PermissionGroupInfo> out
4419                    = new ArrayList<PermissionGroupInfo>(N);
4420            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4421                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4422            }
4423            return new ParceledListSlice<>(out);
4424        }
4425    }
4426
4427    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4428            int filterCallingUid, int userId) {
4429        if (!sUserManager.exists(userId)) return null;
4430        PackageSetting ps = mSettings.mPackages.get(packageName);
4431        if (ps != null) {
4432            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4433                return null;
4434            }
4435            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4436                return null;
4437            }
4438            if (ps.pkg == null) {
4439                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4440                if (pInfo != null) {
4441                    return pInfo.applicationInfo;
4442                }
4443                return null;
4444            }
4445            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4446                    ps.readUserState(userId), userId);
4447            if (ai != null) {
4448                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4449            }
4450            return ai;
4451        }
4452        return null;
4453    }
4454
4455    @Override
4456    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4457        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4458    }
4459
4460    /**
4461     * Important: The provided filterCallingUid is used exclusively to filter out applications
4462     * that can be seen based on user state. It's typically the original caller uid prior
4463     * to clearing. Because it can only be provided by trusted code, it's value can be
4464     * trusted and will be used as-is; unlike userId which will be validated by this method.
4465     */
4466    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4467            int filterCallingUid, int userId) {
4468        if (!sUserManager.exists(userId)) return null;
4469        flags = updateFlagsForApplication(flags, userId, packageName);
4470        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4471                false /* requireFullPermission */, false /* checkShell */, "get application info");
4472
4473        // writer
4474        synchronized (mPackages) {
4475            // Normalize package name to handle renamed packages and static libs
4476            packageName = resolveInternalPackageNameLPr(packageName,
4477                    PackageManager.VERSION_CODE_HIGHEST);
4478
4479            PackageParser.Package p = mPackages.get(packageName);
4480            if (DEBUG_PACKAGE_INFO) Log.v(
4481                    TAG, "getApplicationInfo " + packageName
4482                    + ": " + p);
4483            if (p != null) {
4484                PackageSetting ps = mSettings.mPackages.get(packageName);
4485                if (ps == null) return null;
4486                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4487                    return null;
4488                }
4489                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4490                    return null;
4491                }
4492                // Note: isEnabledLP() does not apply here - always return info
4493                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4494                        p, flags, ps.readUserState(userId), userId);
4495                if (ai != null) {
4496                    ai.packageName = resolveExternalPackageNameLPr(p);
4497                }
4498                return ai;
4499            }
4500            if ("android".equals(packageName)||"system".equals(packageName)) {
4501                return mAndroidApplication;
4502            }
4503            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4504                // Already generates the external package name
4505                return generateApplicationInfoFromSettingsLPw(packageName,
4506                        flags, filterCallingUid, userId);
4507            }
4508        }
4509        return null;
4510    }
4511
4512    private String normalizePackageNameLPr(String packageName) {
4513        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4514        return normalizedPackageName != null ? normalizedPackageName : packageName;
4515    }
4516
4517    @Override
4518    public void deletePreloadsFileCache() {
4519        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4520            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4521        }
4522        File dir = Environment.getDataPreloadsFileCacheDirectory();
4523        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4524        FileUtils.deleteContents(dir);
4525    }
4526
4527    @Override
4528    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4529            final int storageFlags, final IPackageDataObserver observer) {
4530        mContext.enforceCallingOrSelfPermission(
4531                android.Manifest.permission.CLEAR_APP_CACHE, null);
4532        mHandler.post(() -> {
4533            boolean success = false;
4534            try {
4535                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4536                success = true;
4537            } catch (IOException e) {
4538                Slog.w(TAG, e);
4539            }
4540            if (observer != null) {
4541                try {
4542                    observer.onRemoveCompleted(null, success);
4543                } catch (RemoteException e) {
4544                    Slog.w(TAG, e);
4545                }
4546            }
4547        });
4548    }
4549
4550    @Override
4551    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4552            final int storageFlags, final IntentSender pi) {
4553        mContext.enforceCallingOrSelfPermission(
4554                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4555        mHandler.post(() -> {
4556            boolean success = false;
4557            try {
4558                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4559                success = true;
4560            } catch (IOException e) {
4561                Slog.w(TAG, e);
4562            }
4563            if (pi != null) {
4564                try {
4565                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4566                } catch (SendIntentException e) {
4567                    Slog.w(TAG, e);
4568                }
4569            }
4570        });
4571    }
4572
4573    /**
4574     * Blocking call to clear various types of cached data across the system
4575     * until the requested bytes are available.
4576     */
4577    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4578        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4579        final File file = storage.findPathForUuid(volumeUuid);
4580        if (file.getUsableSpace() >= bytes) return;
4581
4582        if (ENABLE_FREE_CACHE_V2) {
4583            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4584                    volumeUuid);
4585            final boolean aggressive = (storageFlags
4586                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4587            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4588
4589            // 1. Pre-flight to determine if we have any chance to succeed
4590            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4591            if (internalVolume && (aggressive || SystemProperties
4592                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4593                deletePreloadsFileCache();
4594                if (file.getUsableSpace() >= bytes) return;
4595            }
4596
4597            // 3. Consider parsed APK data (aggressive only)
4598            if (internalVolume && aggressive) {
4599                FileUtils.deleteContents(mCacheDir);
4600                if (file.getUsableSpace() >= bytes) return;
4601            }
4602
4603            // 4. Consider cached app data (above quotas)
4604            try {
4605                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4606                        Installer.FLAG_FREE_CACHE_V2);
4607            } catch (InstallerException ignored) {
4608            }
4609            if (file.getUsableSpace() >= bytes) return;
4610
4611            // 5. Consider shared libraries with refcount=0 and age>min cache period
4612            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4613                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4614                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4615                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4616                return;
4617            }
4618
4619            // 6. Consider dexopt output (aggressive only)
4620            // TODO: Implement
4621
4622            // 7. Consider installed instant apps unused longer than min cache period
4623            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4624                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4625                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4626                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4627                return;
4628            }
4629
4630            // 8. Consider cached app data (below quotas)
4631            try {
4632                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4633                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4634            } catch (InstallerException ignored) {
4635            }
4636            if (file.getUsableSpace() >= bytes) return;
4637
4638            // 9. Consider DropBox entries
4639            // TODO: Implement
4640
4641            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4642            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4643                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4644                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4645                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4646                return;
4647            }
4648        } else {
4649            try {
4650                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4651            } catch (InstallerException ignored) {
4652            }
4653            if (file.getUsableSpace() >= bytes) return;
4654        }
4655
4656        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4657    }
4658
4659    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4660            throws IOException {
4661        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4662        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4663
4664        List<VersionedPackage> packagesToDelete = null;
4665        final long now = System.currentTimeMillis();
4666
4667        synchronized (mPackages) {
4668            final int[] allUsers = sUserManager.getUserIds();
4669            final int libCount = mSharedLibraries.size();
4670            for (int i = 0; i < libCount; i++) {
4671                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4672                if (versionedLib == null) {
4673                    continue;
4674                }
4675                final int versionCount = versionedLib.size();
4676                for (int j = 0; j < versionCount; j++) {
4677                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4678                    // Skip packages that are not static shared libs.
4679                    if (!libInfo.isStatic()) {
4680                        break;
4681                    }
4682                    // Important: We skip static shared libs used for some user since
4683                    // in such a case we need to keep the APK on the device. The check for
4684                    // a lib being used for any user is performed by the uninstall call.
4685                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4686                    // Resolve the package name - we use synthetic package names internally
4687                    final String internalPackageName = resolveInternalPackageNameLPr(
4688                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4689                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4690                    // Skip unused static shared libs cached less than the min period
4691                    // to prevent pruning a lib needed by a subsequently installed package.
4692                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4693                        continue;
4694                    }
4695                    if (packagesToDelete == null) {
4696                        packagesToDelete = new ArrayList<>();
4697                    }
4698                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4699                            declaringPackage.getVersionCode()));
4700                }
4701            }
4702        }
4703
4704        if (packagesToDelete != null) {
4705            final int packageCount = packagesToDelete.size();
4706            for (int i = 0; i < packageCount; i++) {
4707                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4708                // Delete the package synchronously (will fail of the lib used for any user).
4709                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4710                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4711                                == PackageManager.DELETE_SUCCEEDED) {
4712                    if (volume.getUsableSpace() >= neededSpace) {
4713                        return true;
4714                    }
4715                }
4716            }
4717        }
4718
4719        return false;
4720    }
4721
4722    /**
4723     * Update given flags based on encryption status of current user.
4724     */
4725    private int updateFlags(int flags, int userId) {
4726        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4727                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4728            // Caller expressed an explicit opinion about what encryption
4729            // aware/unaware components they want to see, so fall through and
4730            // give them what they want
4731        } else {
4732            // Caller expressed no opinion, so match based on user state
4733            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4734                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4735            } else {
4736                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4737            }
4738        }
4739        return flags;
4740    }
4741
4742    private UserManagerInternal getUserManagerInternal() {
4743        if (mUserManagerInternal == null) {
4744            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4745        }
4746        return mUserManagerInternal;
4747    }
4748
4749    private DeviceIdleController.LocalService getDeviceIdleController() {
4750        if (mDeviceIdleController == null) {
4751            mDeviceIdleController =
4752                    LocalServices.getService(DeviceIdleController.LocalService.class);
4753        }
4754        return mDeviceIdleController;
4755    }
4756
4757    /**
4758     * Update given flags when being used to request {@link PackageInfo}.
4759     */
4760    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4761        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4762        boolean triaged = true;
4763        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4764                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4765            // Caller is asking for component details, so they'd better be
4766            // asking for specific encryption matching behavior, or be triaged
4767            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4768                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4769                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4770                triaged = false;
4771            }
4772        }
4773        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4774                | PackageManager.MATCH_SYSTEM_ONLY
4775                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4776            triaged = false;
4777        }
4778        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4779            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4780                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4781                    + Debug.getCallers(5));
4782        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4783                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4784            // If the caller wants all packages and has a restricted profile associated with it,
4785            // then match all users. This is to make sure that launchers that need to access work
4786            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4787            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4788            flags |= PackageManager.MATCH_ANY_USER;
4789        }
4790        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4791            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4792                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4793        }
4794        return updateFlags(flags, userId);
4795    }
4796
4797    /**
4798     * Update given flags when being used to request {@link ApplicationInfo}.
4799     */
4800    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4801        return updateFlagsForPackage(flags, userId, cookie);
4802    }
4803
4804    /**
4805     * Update given flags when being used to request {@link ComponentInfo}.
4806     */
4807    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4808        if (cookie instanceof Intent) {
4809            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4810                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4811            }
4812        }
4813
4814        boolean triaged = true;
4815        // Caller is asking for component details, so they'd better be
4816        // asking for specific encryption matching behavior, or be triaged
4817        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4818                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4819                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4820            triaged = false;
4821        }
4822        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4823            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4824                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4825        }
4826
4827        return updateFlags(flags, userId);
4828    }
4829
4830    /**
4831     * Update given intent when being used to request {@link ResolveInfo}.
4832     */
4833    private Intent updateIntentForResolve(Intent intent) {
4834        if (intent.getSelector() != null) {
4835            intent = intent.getSelector();
4836        }
4837        if (DEBUG_PREFERRED) {
4838            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4839        }
4840        return intent;
4841    }
4842
4843    /**
4844     * Update given flags when being used to request {@link ResolveInfo}.
4845     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4846     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4847     * flag set. However, this flag is only honoured in three circumstances:
4848     * <ul>
4849     * <li>when called from a system process</li>
4850     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4851     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4852     * action and a {@code android.intent.category.BROWSABLE} category</li>
4853     * </ul>
4854     */
4855    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4856        return updateFlagsForResolve(flags, userId, intent, callingUid,
4857                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4858    }
4859    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4860            boolean wantInstantApps) {
4861        return updateFlagsForResolve(flags, userId, intent, callingUid,
4862                wantInstantApps, false /*onlyExposedExplicitly*/);
4863    }
4864    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4865            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4866        // Safe mode means we shouldn't match any third-party components
4867        if (mSafeMode) {
4868            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4869        }
4870        if (getInstantAppPackageName(callingUid) != null) {
4871            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4872            if (onlyExposedExplicitly) {
4873                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4874            }
4875            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4876            flags |= PackageManager.MATCH_INSTANT;
4877        } else {
4878            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4879            final boolean allowMatchInstant =
4880                    (wantInstantApps
4881                            && Intent.ACTION_VIEW.equals(intent.getAction())
4882                            && hasWebURI(intent))
4883                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4884            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4885                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4886            if (!allowMatchInstant) {
4887                flags &= ~PackageManager.MATCH_INSTANT;
4888            }
4889        }
4890        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4891    }
4892
4893    @Override
4894    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4895        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4896    }
4897
4898    /**
4899     * Important: The provided filterCallingUid is used exclusively to filter out activities
4900     * that can be seen based on user state. It's typically the original caller uid prior
4901     * to clearing. Because it can only be provided by trusted code, it's value can be
4902     * trusted and will be used as-is; unlike userId which will be validated by this method.
4903     */
4904    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4905            int filterCallingUid, int userId) {
4906        if (!sUserManager.exists(userId)) return null;
4907        flags = updateFlagsForComponent(flags, userId, component);
4908        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4909                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4910        synchronized (mPackages) {
4911            PackageParser.Activity a = mActivities.mActivities.get(component);
4912
4913            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4914            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4915                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4916                if (ps == null) return null;
4917                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4918                    return null;
4919                }
4920                return PackageParser.generateActivityInfo(
4921                        a, flags, ps.readUserState(userId), userId);
4922            }
4923            if (mResolveComponentName.equals(component)) {
4924                return PackageParser.generateActivityInfo(
4925                        mResolveActivity, flags, new PackageUserState(), userId);
4926            }
4927        }
4928        return null;
4929    }
4930
4931    @Override
4932    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4933            String resolvedType) {
4934        synchronized (mPackages) {
4935            if (component.equals(mResolveComponentName)) {
4936                // The resolver supports EVERYTHING!
4937                return true;
4938            }
4939            final int callingUid = Binder.getCallingUid();
4940            final int callingUserId = UserHandle.getUserId(callingUid);
4941            PackageParser.Activity a = mActivities.mActivities.get(component);
4942            if (a == null) {
4943                return false;
4944            }
4945            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4946            if (ps == null) {
4947                return false;
4948            }
4949            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4950                return false;
4951            }
4952            for (int i=0; i<a.intents.size(); i++) {
4953                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4954                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4955                    return true;
4956                }
4957            }
4958            return false;
4959        }
4960    }
4961
4962    @Override
4963    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4964        if (!sUserManager.exists(userId)) return null;
4965        final int callingUid = Binder.getCallingUid();
4966        flags = updateFlagsForComponent(flags, userId, component);
4967        enforceCrossUserPermission(callingUid, userId,
4968                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4969        synchronized (mPackages) {
4970            PackageParser.Activity a = mReceivers.mActivities.get(component);
4971            if (DEBUG_PACKAGE_INFO) Log.v(
4972                TAG, "getReceiverInfo " + component + ": " + a);
4973            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4974                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4975                if (ps == null) return null;
4976                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4977                    return null;
4978                }
4979                return PackageParser.generateActivityInfo(
4980                        a, flags, ps.readUserState(userId), userId);
4981            }
4982        }
4983        return null;
4984    }
4985
4986    @Override
4987    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4988            int flags, int userId) {
4989        if (!sUserManager.exists(userId)) return null;
4990        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4991        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4992            return null;
4993        }
4994
4995        flags = updateFlagsForPackage(flags, userId, null);
4996
4997        final boolean canSeeStaticLibraries =
4998                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4999                        == PERMISSION_GRANTED
5000                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5001                        == PERMISSION_GRANTED
5002                || canRequestPackageInstallsInternal(packageName,
5003                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5004                        false  /* throwIfPermNotDeclared*/)
5005                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5006                        == PERMISSION_GRANTED;
5007
5008        synchronized (mPackages) {
5009            List<SharedLibraryInfo> result = null;
5010
5011            final int libCount = mSharedLibraries.size();
5012            for (int i = 0; i < libCount; i++) {
5013                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5014                if (versionedLib == null) {
5015                    continue;
5016                }
5017
5018                final int versionCount = versionedLib.size();
5019                for (int j = 0; j < versionCount; j++) {
5020                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5021                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5022                        break;
5023                    }
5024                    final long identity = Binder.clearCallingIdentity();
5025                    try {
5026                        PackageInfo packageInfo = getPackageInfoVersioned(
5027                                libInfo.getDeclaringPackage(), flags
5028                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5029                        if (packageInfo == null) {
5030                            continue;
5031                        }
5032                    } finally {
5033                        Binder.restoreCallingIdentity(identity);
5034                    }
5035
5036                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5037                            libInfo.getVersion(), libInfo.getType(),
5038                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5039                            flags, userId));
5040
5041                    if (result == null) {
5042                        result = new ArrayList<>();
5043                    }
5044                    result.add(resLibInfo);
5045                }
5046            }
5047
5048            return result != null ? new ParceledListSlice<>(result) : null;
5049        }
5050    }
5051
5052    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5053            SharedLibraryInfo libInfo, int flags, int userId) {
5054        List<VersionedPackage> versionedPackages = null;
5055        final int packageCount = mSettings.mPackages.size();
5056        for (int i = 0; i < packageCount; i++) {
5057            PackageSetting ps = mSettings.mPackages.valueAt(i);
5058
5059            if (ps == null) {
5060                continue;
5061            }
5062
5063            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5064                continue;
5065            }
5066
5067            final String libName = libInfo.getName();
5068            if (libInfo.isStatic()) {
5069                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5070                if (libIdx < 0) {
5071                    continue;
5072                }
5073                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5074                    continue;
5075                }
5076                if (versionedPackages == null) {
5077                    versionedPackages = new ArrayList<>();
5078                }
5079                // If the dependent is a static shared lib, use the public package name
5080                String dependentPackageName = ps.name;
5081                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5082                    dependentPackageName = ps.pkg.manifestPackageName;
5083                }
5084                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5085            } else if (ps.pkg != null) {
5086                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5087                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5088                    if (versionedPackages == null) {
5089                        versionedPackages = new ArrayList<>();
5090                    }
5091                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5092                }
5093            }
5094        }
5095
5096        return versionedPackages;
5097    }
5098
5099    @Override
5100    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5101        if (!sUserManager.exists(userId)) return null;
5102        final int callingUid = Binder.getCallingUid();
5103        flags = updateFlagsForComponent(flags, userId, component);
5104        enforceCrossUserPermission(callingUid, userId,
5105                false /* requireFullPermission */, false /* checkShell */, "get service info");
5106        synchronized (mPackages) {
5107            PackageParser.Service s = mServices.mServices.get(component);
5108            if (DEBUG_PACKAGE_INFO) Log.v(
5109                TAG, "getServiceInfo " + component + ": " + s);
5110            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5111                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5112                if (ps == null) return null;
5113                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5114                    return null;
5115                }
5116                return PackageParser.generateServiceInfo(
5117                        s, flags, ps.readUserState(userId), userId);
5118            }
5119        }
5120        return null;
5121    }
5122
5123    @Override
5124    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5125        if (!sUserManager.exists(userId)) return null;
5126        final int callingUid = Binder.getCallingUid();
5127        flags = updateFlagsForComponent(flags, userId, component);
5128        enforceCrossUserPermission(callingUid, userId,
5129                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5130        synchronized (mPackages) {
5131            PackageParser.Provider p = mProviders.mProviders.get(component);
5132            if (DEBUG_PACKAGE_INFO) Log.v(
5133                TAG, "getProviderInfo " + component + ": " + p);
5134            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5135                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5136                if (ps == null) return null;
5137                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5138                    return null;
5139                }
5140                return PackageParser.generateProviderInfo(
5141                        p, flags, ps.readUserState(userId), userId);
5142            }
5143        }
5144        return null;
5145    }
5146
5147    @Override
5148    public String[] getSystemSharedLibraryNames() {
5149        // allow instant applications
5150        synchronized (mPackages) {
5151            Set<String> libs = null;
5152            final int libCount = mSharedLibraries.size();
5153            for (int i = 0; i < libCount; i++) {
5154                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5155                if (versionedLib == null) {
5156                    continue;
5157                }
5158                final int versionCount = versionedLib.size();
5159                for (int j = 0; j < versionCount; j++) {
5160                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5161                    if (!libEntry.info.isStatic()) {
5162                        if (libs == null) {
5163                            libs = new ArraySet<>();
5164                        }
5165                        libs.add(libEntry.info.getName());
5166                        break;
5167                    }
5168                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5169                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5170                            UserHandle.getUserId(Binder.getCallingUid()),
5171                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5172                        if (libs == null) {
5173                            libs = new ArraySet<>();
5174                        }
5175                        libs.add(libEntry.info.getName());
5176                        break;
5177                    }
5178                }
5179            }
5180
5181            if (libs != null) {
5182                String[] libsArray = new String[libs.size()];
5183                libs.toArray(libsArray);
5184                return libsArray;
5185            }
5186
5187            return null;
5188        }
5189    }
5190
5191    @Override
5192    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5193        // allow instant applications
5194        synchronized (mPackages) {
5195            return mServicesSystemSharedLibraryPackageName;
5196        }
5197    }
5198
5199    @Override
5200    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5201        // allow instant applications
5202        synchronized (mPackages) {
5203            return mSharedSystemSharedLibraryPackageName;
5204        }
5205    }
5206
5207    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5208        for (int i = userList.length - 1; i >= 0; --i) {
5209            final int userId = userList[i];
5210            // don't add instant app to the list of updates
5211            if (pkgSetting.getInstantApp(userId)) {
5212                continue;
5213            }
5214            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5215            if (changedPackages == null) {
5216                changedPackages = new SparseArray<>();
5217                mChangedPackages.put(userId, changedPackages);
5218            }
5219            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5220            if (sequenceNumbers == null) {
5221                sequenceNumbers = new HashMap<>();
5222                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5223            }
5224            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5225            if (sequenceNumber != null) {
5226                changedPackages.remove(sequenceNumber);
5227            }
5228            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5229            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5230        }
5231        mChangedPackagesSequenceNumber++;
5232    }
5233
5234    @Override
5235    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5236        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5237            return null;
5238        }
5239        synchronized (mPackages) {
5240            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5241                return null;
5242            }
5243            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5244            if (changedPackages == null) {
5245                return null;
5246            }
5247            final List<String> packageNames =
5248                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5249            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5250                final String packageName = changedPackages.get(i);
5251                if (packageName != null) {
5252                    packageNames.add(packageName);
5253                }
5254            }
5255            return packageNames.isEmpty()
5256                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5257        }
5258    }
5259
5260    @Override
5261    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5262        // allow instant applications
5263        ArrayList<FeatureInfo> res;
5264        synchronized (mAvailableFeatures) {
5265            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5266            res.addAll(mAvailableFeatures.values());
5267        }
5268        final FeatureInfo fi = new FeatureInfo();
5269        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5270                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5271        res.add(fi);
5272
5273        return new ParceledListSlice<>(res);
5274    }
5275
5276    @Override
5277    public boolean hasSystemFeature(String name, int version) {
5278        // allow instant applications
5279        synchronized (mAvailableFeatures) {
5280            final FeatureInfo feat = mAvailableFeatures.get(name);
5281            if (feat == null) {
5282                return false;
5283            } else {
5284                return feat.version >= version;
5285            }
5286        }
5287    }
5288
5289    @Override
5290    public int checkPermission(String permName, String pkgName, int userId) {
5291        if (!sUserManager.exists(userId)) {
5292            return PackageManager.PERMISSION_DENIED;
5293        }
5294        final int callingUid = Binder.getCallingUid();
5295
5296        synchronized (mPackages) {
5297            final PackageParser.Package p = mPackages.get(pkgName);
5298            if (p != null && p.mExtras != null) {
5299                final PackageSetting ps = (PackageSetting) p.mExtras;
5300                if (filterAppAccessLPr(ps, callingUid, userId)) {
5301                    return PackageManager.PERMISSION_DENIED;
5302                }
5303                final boolean instantApp = ps.getInstantApp(userId);
5304                final PermissionsState permissionsState = ps.getPermissionsState();
5305                if (permissionsState.hasPermission(permName, userId)) {
5306                    if (instantApp) {
5307                        BasePermission bp = mSettings.mPermissions.get(permName);
5308                        if (bp != null && bp.isInstant()) {
5309                            return PackageManager.PERMISSION_GRANTED;
5310                        }
5311                    } else {
5312                        return PackageManager.PERMISSION_GRANTED;
5313                    }
5314                }
5315                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5316                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5317                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5318                    return PackageManager.PERMISSION_GRANTED;
5319                }
5320            }
5321        }
5322
5323        return PackageManager.PERMISSION_DENIED;
5324    }
5325
5326    @Override
5327    public int checkUidPermission(String permName, int uid) {
5328        final int callingUid = Binder.getCallingUid();
5329        final int callingUserId = UserHandle.getUserId(callingUid);
5330        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5331        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5332        final int userId = UserHandle.getUserId(uid);
5333        if (!sUserManager.exists(userId)) {
5334            return PackageManager.PERMISSION_DENIED;
5335        }
5336
5337        synchronized (mPackages) {
5338            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5339            if (obj != null) {
5340                if (obj instanceof SharedUserSetting) {
5341                    if (isCallerInstantApp) {
5342                        return PackageManager.PERMISSION_DENIED;
5343                    }
5344                } else if (obj instanceof PackageSetting) {
5345                    final PackageSetting ps = (PackageSetting) obj;
5346                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5347                        return PackageManager.PERMISSION_DENIED;
5348                    }
5349                }
5350                final SettingBase settingBase = (SettingBase) obj;
5351                final PermissionsState permissionsState = settingBase.getPermissionsState();
5352                if (permissionsState.hasPermission(permName, userId)) {
5353                    if (isUidInstantApp) {
5354                        BasePermission bp = mSettings.mPermissions.get(permName);
5355                        if (bp != null && bp.isInstant()) {
5356                            return PackageManager.PERMISSION_GRANTED;
5357                        }
5358                    } else {
5359                        return PackageManager.PERMISSION_GRANTED;
5360                    }
5361                }
5362                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5363                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5364                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5365                    return PackageManager.PERMISSION_GRANTED;
5366                }
5367            } else {
5368                ArraySet<String> perms = mSystemPermissions.get(uid);
5369                if (perms != null) {
5370                    if (perms.contains(permName)) {
5371                        return PackageManager.PERMISSION_GRANTED;
5372                    }
5373                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5374                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5375                        return PackageManager.PERMISSION_GRANTED;
5376                    }
5377                }
5378            }
5379        }
5380
5381        return PackageManager.PERMISSION_DENIED;
5382    }
5383
5384    @Override
5385    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5386        if (UserHandle.getCallingUserId() != userId) {
5387            mContext.enforceCallingPermission(
5388                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5389                    "isPermissionRevokedByPolicy for user " + userId);
5390        }
5391
5392        if (checkPermission(permission, packageName, userId)
5393                == PackageManager.PERMISSION_GRANTED) {
5394            return false;
5395        }
5396
5397        final int callingUid = Binder.getCallingUid();
5398        if (getInstantAppPackageName(callingUid) != null) {
5399            if (!isCallerSameApp(packageName, callingUid)) {
5400                return false;
5401            }
5402        } else {
5403            if (isInstantApp(packageName, userId)) {
5404                return false;
5405            }
5406        }
5407
5408        final long identity = Binder.clearCallingIdentity();
5409        try {
5410            final int flags = getPermissionFlags(permission, packageName, userId);
5411            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5412        } finally {
5413            Binder.restoreCallingIdentity(identity);
5414        }
5415    }
5416
5417    @Override
5418    public String getPermissionControllerPackageName() {
5419        synchronized (mPackages) {
5420            return mRequiredInstallerPackage;
5421        }
5422    }
5423
5424    /**
5425     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5426     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5427     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5428     * @param message the message to log on security exception
5429     */
5430    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5431            boolean checkShell, String message) {
5432        if (userId < 0) {
5433            throw new IllegalArgumentException("Invalid userId " + userId);
5434        }
5435        if (checkShell) {
5436            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5437        }
5438        if (userId == UserHandle.getUserId(callingUid)) return;
5439        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5440            if (requireFullPermission) {
5441                mContext.enforceCallingOrSelfPermission(
5442                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5443            } else {
5444                try {
5445                    mContext.enforceCallingOrSelfPermission(
5446                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5447                } catch (SecurityException se) {
5448                    mContext.enforceCallingOrSelfPermission(
5449                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5450                }
5451            }
5452        }
5453    }
5454
5455    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5456        if (callingUid == Process.SHELL_UID) {
5457            if (userHandle >= 0
5458                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5459                throw new SecurityException("Shell does not have permission to access user "
5460                        + userHandle);
5461            } else if (userHandle < 0) {
5462                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5463                        + Debug.getCallers(3));
5464            }
5465        }
5466    }
5467
5468    private BasePermission findPermissionTreeLP(String permName) {
5469        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5470            if (permName.startsWith(bp.name) &&
5471                    permName.length() > bp.name.length() &&
5472                    permName.charAt(bp.name.length()) == '.') {
5473                return bp;
5474            }
5475        }
5476        return null;
5477    }
5478
5479    private BasePermission checkPermissionTreeLP(String permName) {
5480        if (permName != null) {
5481            BasePermission bp = findPermissionTreeLP(permName);
5482            if (bp != null) {
5483                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5484                    return bp;
5485                }
5486                throw new SecurityException("Calling uid "
5487                        + Binder.getCallingUid()
5488                        + " is not allowed to add to permission tree "
5489                        + bp.name + " owned by uid " + bp.uid);
5490            }
5491        }
5492        throw new SecurityException("No permission tree found for " + permName);
5493    }
5494
5495    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5496        if (s1 == null) {
5497            return s2 == null;
5498        }
5499        if (s2 == null) {
5500            return false;
5501        }
5502        if (s1.getClass() != s2.getClass()) {
5503            return false;
5504        }
5505        return s1.equals(s2);
5506    }
5507
5508    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5509        if (pi1.icon != pi2.icon) return false;
5510        if (pi1.logo != pi2.logo) return false;
5511        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5512        if (!compareStrings(pi1.name, pi2.name)) return false;
5513        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5514        // We'll take care of setting this one.
5515        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5516        // These are not currently stored in settings.
5517        //if (!compareStrings(pi1.group, pi2.group)) return false;
5518        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5519        //if (pi1.labelRes != pi2.labelRes) return false;
5520        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5521        return true;
5522    }
5523
5524    int permissionInfoFootprint(PermissionInfo info) {
5525        int size = info.name.length();
5526        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5527        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5528        return size;
5529    }
5530
5531    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5532        int size = 0;
5533        for (BasePermission perm : mSettings.mPermissions.values()) {
5534            if (perm.uid == tree.uid) {
5535                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5536            }
5537        }
5538        return size;
5539    }
5540
5541    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5542        // We calculate the max size of permissions defined by this uid and throw
5543        // if that plus the size of 'info' would exceed our stated maximum.
5544        if (tree.uid != Process.SYSTEM_UID) {
5545            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5546            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5547                throw new SecurityException("Permission tree size cap exceeded");
5548            }
5549        }
5550    }
5551
5552    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5553        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5554            throw new SecurityException("Instant apps can't add permissions");
5555        }
5556        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5557            throw new SecurityException("Label must be specified in permission");
5558        }
5559        BasePermission tree = checkPermissionTreeLP(info.name);
5560        BasePermission bp = mSettings.mPermissions.get(info.name);
5561        boolean added = bp == null;
5562        boolean changed = true;
5563        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5564        if (added) {
5565            enforcePermissionCapLocked(info, tree);
5566            bp = new BasePermission(info.name, tree.sourcePackage,
5567                    BasePermission.TYPE_DYNAMIC);
5568        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5569            throw new SecurityException(
5570                    "Not allowed to modify non-dynamic permission "
5571                    + info.name);
5572        } else {
5573            if (bp.protectionLevel == fixedLevel
5574                    && bp.perm.owner.equals(tree.perm.owner)
5575                    && bp.uid == tree.uid
5576                    && comparePermissionInfos(bp.perm.info, info)) {
5577                changed = false;
5578            }
5579        }
5580        bp.protectionLevel = fixedLevel;
5581        info = new PermissionInfo(info);
5582        info.protectionLevel = fixedLevel;
5583        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5584        bp.perm.info.packageName = tree.perm.info.packageName;
5585        bp.uid = tree.uid;
5586        if (added) {
5587            mSettings.mPermissions.put(info.name, bp);
5588        }
5589        if (changed) {
5590            if (!async) {
5591                mSettings.writeLPr();
5592            } else {
5593                scheduleWriteSettingsLocked();
5594            }
5595        }
5596        return added;
5597    }
5598
5599    @Override
5600    public boolean addPermission(PermissionInfo info) {
5601        synchronized (mPackages) {
5602            return addPermissionLocked(info, false);
5603        }
5604    }
5605
5606    @Override
5607    public boolean addPermissionAsync(PermissionInfo info) {
5608        synchronized (mPackages) {
5609            return addPermissionLocked(info, true);
5610        }
5611    }
5612
5613    @Override
5614    public void removePermission(String name) {
5615        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5616            throw new SecurityException("Instant applications don't have access to this method");
5617        }
5618        synchronized (mPackages) {
5619            checkPermissionTreeLP(name);
5620            BasePermission bp = mSettings.mPermissions.get(name);
5621            if (bp != null) {
5622                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5623                    throw new SecurityException(
5624                            "Not allowed to modify non-dynamic permission "
5625                            + name);
5626                }
5627                mSettings.mPermissions.remove(name);
5628                mSettings.writeLPr();
5629            }
5630        }
5631    }
5632
5633    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5634            PackageParser.Package pkg, BasePermission bp) {
5635        int index = pkg.requestedPermissions.indexOf(bp.name);
5636        if (index == -1) {
5637            throw new SecurityException("Package " + pkg.packageName
5638                    + " has not requested permission " + bp.name);
5639        }
5640        if (!bp.isRuntime() && !bp.isDevelopment()) {
5641            throw new SecurityException("Permission " + bp.name
5642                    + " is not a changeable permission type");
5643        }
5644    }
5645
5646    @Override
5647    public void grantRuntimePermission(String packageName, String name, final int userId) {
5648        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5649    }
5650
5651    private void grantRuntimePermission(String packageName, String name, final int userId,
5652            boolean overridePolicy) {
5653        if (!sUserManager.exists(userId)) {
5654            Log.e(TAG, "No such user:" + userId);
5655            return;
5656        }
5657        final int callingUid = Binder.getCallingUid();
5658
5659        mContext.enforceCallingOrSelfPermission(
5660                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5661                "grantRuntimePermission");
5662
5663        enforceCrossUserPermission(callingUid, userId,
5664                true /* requireFullPermission */, true /* checkShell */,
5665                "grantRuntimePermission");
5666
5667        final int uid;
5668        final PackageSetting ps;
5669
5670        synchronized (mPackages) {
5671            final PackageParser.Package pkg = mPackages.get(packageName);
5672            if (pkg == null) {
5673                throw new IllegalArgumentException("Unknown package: " + packageName);
5674            }
5675            final BasePermission bp = mSettings.mPermissions.get(name);
5676            if (bp == null) {
5677                throw new IllegalArgumentException("Unknown permission: " + name);
5678            }
5679            ps = (PackageSetting) pkg.mExtras;
5680            if (ps == null
5681                    || filterAppAccessLPr(ps, callingUid, userId)) {
5682                throw new IllegalArgumentException("Unknown package: " + packageName);
5683            }
5684
5685            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5686
5687            // If a permission review is required for legacy apps we represent
5688            // their permissions as always granted runtime ones since we need
5689            // to keep the review required permission flag per user while an
5690            // install permission's state is shared across all users.
5691            if (mPermissionReviewRequired
5692                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5693                    && bp.isRuntime()) {
5694                return;
5695            }
5696
5697            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5698
5699            final PermissionsState permissionsState = ps.getPermissionsState();
5700
5701            final int flags = permissionsState.getPermissionFlags(name, userId);
5702            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5703                throw new SecurityException("Cannot grant system fixed permission "
5704                        + name + " for package " + packageName);
5705            }
5706            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5707                throw new SecurityException("Cannot grant policy fixed permission "
5708                        + name + " for package " + packageName);
5709            }
5710
5711            if (bp.isDevelopment()) {
5712                // Development permissions must be handled specially, since they are not
5713                // normal runtime permissions.  For now they apply to all users.
5714                if (permissionsState.grantInstallPermission(bp) !=
5715                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5716                    scheduleWriteSettingsLocked();
5717                }
5718                return;
5719            }
5720
5721            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5722                throw new SecurityException("Cannot grant non-ephemeral permission"
5723                        + name + " for package " + packageName);
5724            }
5725
5726            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5727                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5728                return;
5729            }
5730
5731            final int result = permissionsState.grantRuntimePermission(bp, userId);
5732            switch (result) {
5733                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5734                    return;
5735                }
5736
5737                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5738                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5739                    mHandler.post(new Runnable() {
5740                        @Override
5741                        public void run() {
5742                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5743                        }
5744                    });
5745                }
5746                break;
5747            }
5748
5749            if (bp.isRuntime()) {
5750                logPermissionGranted(mContext, name, packageName);
5751            }
5752
5753            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5754
5755            // Not critical if that is lost - app has to request again.
5756            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5757        }
5758
5759        // Only need to do this if user is initialized. Otherwise it's a new user
5760        // and there are no processes running as the user yet and there's no need
5761        // to make an expensive call to remount processes for the changed permissions.
5762        if (READ_EXTERNAL_STORAGE.equals(name)
5763                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5764            final long token = Binder.clearCallingIdentity();
5765            try {
5766                if (sUserManager.isInitialized(userId)) {
5767                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5768                            StorageManagerInternal.class);
5769                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5770                }
5771            } finally {
5772                Binder.restoreCallingIdentity(token);
5773            }
5774        }
5775    }
5776
5777    @Override
5778    public void revokeRuntimePermission(String packageName, String name, int userId) {
5779        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5780    }
5781
5782    private void revokeRuntimePermission(String packageName, String name, int userId,
5783            boolean overridePolicy) {
5784        if (!sUserManager.exists(userId)) {
5785            Log.e(TAG, "No such user:" + userId);
5786            return;
5787        }
5788
5789        mContext.enforceCallingOrSelfPermission(
5790                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5791                "revokeRuntimePermission");
5792
5793        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5794                true /* requireFullPermission */, true /* checkShell */,
5795                "revokeRuntimePermission");
5796
5797        final int appId;
5798
5799        synchronized (mPackages) {
5800            final PackageParser.Package pkg = mPackages.get(packageName);
5801            if (pkg == null) {
5802                throw new IllegalArgumentException("Unknown package: " + packageName);
5803            }
5804            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5805            if (ps == null
5806                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5807                throw new IllegalArgumentException("Unknown package: " + packageName);
5808            }
5809            final BasePermission bp = mSettings.mPermissions.get(name);
5810            if (bp == null) {
5811                throw new IllegalArgumentException("Unknown permission: " + name);
5812            }
5813
5814            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5815
5816            // If a permission review is required for legacy apps we represent
5817            // their permissions as always granted runtime ones since we need
5818            // to keep the review required permission flag per user while an
5819            // install permission's state is shared across all users.
5820            if (mPermissionReviewRequired
5821                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5822                    && bp.isRuntime()) {
5823                return;
5824            }
5825
5826            final PermissionsState permissionsState = ps.getPermissionsState();
5827
5828            final int flags = permissionsState.getPermissionFlags(name, userId);
5829            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5830                throw new SecurityException("Cannot revoke system fixed permission "
5831                        + name + " for package " + packageName);
5832            }
5833            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5834                throw new SecurityException("Cannot revoke policy fixed permission "
5835                        + name + " for package " + packageName);
5836            }
5837
5838            if (bp.isDevelopment()) {
5839                // Development permissions must be handled specially, since they are not
5840                // normal runtime permissions.  For now they apply to all users.
5841                if (permissionsState.revokeInstallPermission(bp) !=
5842                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5843                    scheduleWriteSettingsLocked();
5844                }
5845                return;
5846            }
5847
5848            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5849                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5850                return;
5851            }
5852
5853            if (bp.isRuntime()) {
5854                logPermissionRevoked(mContext, name, packageName);
5855            }
5856
5857            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5858
5859            // Critical, after this call app should never have the permission.
5860            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5861
5862            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5863        }
5864
5865        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5866    }
5867
5868    /**
5869     * Get the first event id for the permission.
5870     *
5871     * <p>There are four events for each permission: <ul>
5872     *     <li>Request permission: first id + 0</li>
5873     *     <li>Grant permission: first id + 1</li>
5874     *     <li>Request for permission denied: first id + 2</li>
5875     *     <li>Revoke permission: first id + 3</li>
5876     * </ul></p>
5877     *
5878     * @param name name of the permission
5879     *
5880     * @return The first event id for the permission
5881     */
5882    private static int getBaseEventId(@NonNull String name) {
5883        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5884
5885        if (eventIdIndex == -1) {
5886            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5887                    || Build.IS_USER) {
5888                Log.i(TAG, "Unknown permission " + name);
5889
5890                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5891            } else {
5892                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5893                //
5894                // Also update
5895                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5896                // - metrics_constants.proto
5897                throw new IllegalStateException("Unknown permission " + name);
5898            }
5899        }
5900
5901        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5902    }
5903
5904    /**
5905     * Log that a permission was revoked.
5906     *
5907     * @param context Context of the caller
5908     * @param name name of the permission
5909     * @param packageName package permission if for
5910     */
5911    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5912            @NonNull String packageName) {
5913        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5914    }
5915
5916    /**
5917     * Log that a permission request was granted.
5918     *
5919     * @param context Context of the caller
5920     * @param name name of the permission
5921     * @param packageName package permission if for
5922     */
5923    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5924            @NonNull String packageName) {
5925        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5926    }
5927
5928    @Override
5929    public void resetRuntimePermissions() {
5930        mContext.enforceCallingOrSelfPermission(
5931                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5932                "revokeRuntimePermission");
5933
5934        int callingUid = Binder.getCallingUid();
5935        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5936            mContext.enforceCallingOrSelfPermission(
5937                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5938                    "resetRuntimePermissions");
5939        }
5940
5941        synchronized (mPackages) {
5942            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5943            for (int userId : UserManagerService.getInstance().getUserIds()) {
5944                final int packageCount = mPackages.size();
5945                for (int i = 0; i < packageCount; i++) {
5946                    PackageParser.Package pkg = mPackages.valueAt(i);
5947                    if (!(pkg.mExtras instanceof PackageSetting)) {
5948                        continue;
5949                    }
5950                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5951                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5952                }
5953            }
5954        }
5955    }
5956
5957    @Override
5958    public int getPermissionFlags(String name, String packageName, int userId) {
5959        if (!sUserManager.exists(userId)) {
5960            return 0;
5961        }
5962
5963        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5964
5965        final int callingUid = Binder.getCallingUid();
5966        enforceCrossUserPermission(callingUid, userId,
5967                true /* requireFullPermission */, false /* checkShell */,
5968                "getPermissionFlags");
5969
5970        synchronized (mPackages) {
5971            final PackageParser.Package pkg = mPackages.get(packageName);
5972            if (pkg == null) {
5973                return 0;
5974            }
5975            final BasePermission bp = mSettings.mPermissions.get(name);
5976            if (bp == null) {
5977                return 0;
5978            }
5979            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5980            if (ps == null
5981                    || filterAppAccessLPr(ps, callingUid, userId)) {
5982                return 0;
5983            }
5984            PermissionsState permissionsState = ps.getPermissionsState();
5985            return permissionsState.getPermissionFlags(name, userId);
5986        }
5987    }
5988
5989    @Override
5990    public void updatePermissionFlags(String name, String packageName, int flagMask,
5991            int flagValues, int userId) {
5992        if (!sUserManager.exists(userId)) {
5993            return;
5994        }
5995
5996        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5997
5998        final int callingUid = Binder.getCallingUid();
5999        enforceCrossUserPermission(callingUid, userId,
6000                true /* requireFullPermission */, true /* checkShell */,
6001                "updatePermissionFlags");
6002
6003        // Only the system can change these flags and nothing else.
6004        if (getCallingUid() != Process.SYSTEM_UID) {
6005            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6006            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6007            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
6008            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
6009            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
6010        }
6011
6012        synchronized (mPackages) {
6013            final PackageParser.Package pkg = mPackages.get(packageName);
6014            if (pkg == null) {
6015                throw new IllegalArgumentException("Unknown package: " + packageName);
6016            }
6017            final PackageSetting ps = (PackageSetting) pkg.mExtras;
6018            if (ps == null
6019                    || filterAppAccessLPr(ps, callingUid, userId)) {
6020                throw new IllegalArgumentException("Unknown package: " + packageName);
6021            }
6022
6023            final BasePermission bp = mSettings.mPermissions.get(name);
6024            if (bp == null) {
6025                throw new IllegalArgumentException("Unknown permission: " + name);
6026            }
6027
6028            PermissionsState permissionsState = ps.getPermissionsState();
6029
6030            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6031
6032            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6033                // Install and runtime permissions are stored in different places,
6034                // so figure out what permission changed and persist the change.
6035                if (permissionsState.getInstallPermissionState(name) != null) {
6036                    scheduleWriteSettingsLocked();
6037                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6038                        || hadState) {
6039                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6040                }
6041            }
6042        }
6043    }
6044
6045    /**
6046     * Update the permission flags for all packages and runtime permissions of a user in order
6047     * to allow device or profile owner to remove POLICY_FIXED.
6048     */
6049    @Override
6050    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6051        if (!sUserManager.exists(userId)) {
6052            return;
6053        }
6054
6055        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6056
6057        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6058                true /* requireFullPermission */, true /* checkShell */,
6059                "updatePermissionFlagsForAllApps");
6060
6061        // Only the system can change system fixed flags.
6062        if (getCallingUid() != Process.SYSTEM_UID) {
6063            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6064            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6065        }
6066
6067        synchronized (mPackages) {
6068            boolean changed = false;
6069            final int packageCount = mPackages.size();
6070            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6071                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6072                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6073                if (ps == null) {
6074                    continue;
6075                }
6076                PermissionsState permissionsState = ps.getPermissionsState();
6077                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6078                        userId, flagMask, flagValues);
6079            }
6080            if (changed) {
6081                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6082            }
6083        }
6084    }
6085
6086    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6087        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6088                != PackageManager.PERMISSION_GRANTED
6089            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6090                != PackageManager.PERMISSION_GRANTED) {
6091            throw new SecurityException(message + " requires "
6092                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6093                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6094        }
6095    }
6096
6097    @Override
6098    public boolean shouldShowRequestPermissionRationale(String permissionName,
6099            String packageName, int userId) {
6100        if (UserHandle.getCallingUserId() != userId) {
6101            mContext.enforceCallingPermission(
6102                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6103                    "canShowRequestPermissionRationale for user " + userId);
6104        }
6105
6106        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6107        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6108            return false;
6109        }
6110
6111        if (checkPermission(permissionName, packageName, userId)
6112                == PackageManager.PERMISSION_GRANTED) {
6113            return false;
6114        }
6115
6116        final int flags;
6117
6118        final long identity = Binder.clearCallingIdentity();
6119        try {
6120            flags = getPermissionFlags(permissionName,
6121                    packageName, userId);
6122        } finally {
6123            Binder.restoreCallingIdentity(identity);
6124        }
6125
6126        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6127                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6128                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6129
6130        if ((flags & fixedFlags) != 0) {
6131            return false;
6132        }
6133
6134        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6135    }
6136
6137    @Override
6138    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6139        mContext.enforceCallingOrSelfPermission(
6140                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6141                "addOnPermissionsChangeListener");
6142
6143        synchronized (mPackages) {
6144            mOnPermissionChangeListeners.addListenerLocked(listener);
6145        }
6146    }
6147
6148    @Override
6149    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6150        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6151            throw new SecurityException("Instant applications don't have access to this method");
6152        }
6153        synchronized (mPackages) {
6154            mOnPermissionChangeListeners.removeListenerLocked(listener);
6155        }
6156    }
6157
6158    @Override
6159    public boolean isProtectedBroadcast(String actionName) {
6160        // allow instant applications
6161        synchronized (mProtectedBroadcasts) {
6162            if (mProtectedBroadcasts.contains(actionName)) {
6163                return true;
6164            } else if (actionName != null) {
6165                // TODO: remove these terrible hacks
6166                if (actionName.startsWith("android.net.netmon.lingerExpired")
6167                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6168                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6169                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6170                    return true;
6171                }
6172            }
6173        }
6174        return false;
6175    }
6176
6177    @Override
6178    public int checkSignatures(String pkg1, String pkg2) {
6179        synchronized (mPackages) {
6180            final PackageParser.Package p1 = mPackages.get(pkg1);
6181            final PackageParser.Package p2 = mPackages.get(pkg2);
6182            if (p1 == null || p1.mExtras == null
6183                    || p2 == null || p2.mExtras == null) {
6184                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6185            }
6186            final int callingUid = Binder.getCallingUid();
6187            final int callingUserId = UserHandle.getUserId(callingUid);
6188            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6189            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6190            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6191                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6192                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6193            }
6194            return compareSignatures(p1.mSignatures, p2.mSignatures);
6195        }
6196    }
6197
6198    @Override
6199    public int checkUidSignatures(int uid1, int uid2) {
6200        final int callingUid = Binder.getCallingUid();
6201        final int callingUserId = UserHandle.getUserId(callingUid);
6202        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6203        // Map to base uids.
6204        uid1 = UserHandle.getAppId(uid1);
6205        uid2 = UserHandle.getAppId(uid2);
6206        // reader
6207        synchronized (mPackages) {
6208            Signature[] s1;
6209            Signature[] s2;
6210            Object obj = mSettings.getUserIdLPr(uid1);
6211            if (obj != null) {
6212                if (obj instanceof SharedUserSetting) {
6213                    if (isCallerInstantApp) {
6214                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6215                    }
6216                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6217                } else if (obj instanceof PackageSetting) {
6218                    final PackageSetting ps = (PackageSetting) obj;
6219                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6220                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6221                    }
6222                    s1 = ps.signatures.mSignatures;
6223                } else {
6224                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6225                }
6226            } else {
6227                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6228            }
6229            obj = mSettings.getUserIdLPr(uid2);
6230            if (obj != null) {
6231                if (obj instanceof SharedUserSetting) {
6232                    if (isCallerInstantApp) {
6233                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6234                    }
6235                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6236                } else if (obj instanceof PackageSetting) {
6237                    final PackageSetting ps = (PackageSetting) obj;
6238                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6239                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6240                    }
6241                    s2 = ps.signatures.mSignatures;
6242                } else {
6243                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6244                }
6245            } else {
6246                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6247            }
6248            return compareSignatures(s1, s2);
6249        }
6250    }
6251
6252    /**
6253     * This method should typically only be used when granting or revoking
6254     * permissions, since the app may immediately restart after this call.
6255     * <p>
6256     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6257     * guard your work against the app being relaunched.
6258     */
6259    private void killUid(int appId, int userId, String reason) {
6260        final long identity = Binder.clearCallingIdentity();
6261        try {
6262            IActivityManager am = ActivityManager.getService();
6263            if (am != null) {
6264                try {
6265                    am.killUid(appId, userId, reason);
6266                } catch (RemoteException e) {
6267                    /* ignore - same process */
6268                }
6269            }
6270        } finally {
6271            Binder.restoreCallingIdentity(identity);
6272        }
6273    }
6274
6275    /**
6276     * Compares two sets of signatures. Returns:
6277     * <br />
6278     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6279     * <br />
6280     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6281     * <br />
6282     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6283     * <br />
6284     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6285     * <br />
6286     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6287     */
6288    static int compareSignatures(Signature[] s1, Signature[] s2) {
6289        if (s1 == null) {
6290            return s2 == null
6291                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6292                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6293        }
6294
6295        if (s2 == null) {
6296            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6297        }
6298
6299        if (s1.length != s2.length) {
6300            return PackageManager.SIGNATURE_NO_MATCH;
6301        }
6302
6303        // Since both signature sets are of size 1, we can compare without HashSets.
6304        if (s1.length == 1) {
6305            return s1[0].equals(s2[0]) ?
6306                    PackageManager.SIGNATURE_MATCH :
6307                    PackageManager.SIGNATURE_NO_MATCH;
6308        }
6309
6310        ArraySet<Signature> set1 = new ArraySet<Signature>();
6311        for (Signature sig : s1) {
6312            set1.add(sig);
6313        }
6314        ArraySet<Signature> set2 = new ArraySet<Signature>();
6315        for (Signature sig : s2) {
6316            set2.add(sig);
6317        }
6318        // Make sure s2 contains all signatures in s1.
6319        if (set1.equals(set2)) {
6320            return PackageManager.SIGNATURE_MATCH;
6321        }
6322        return PackageManager.SIGNATURE_NO_MATCH;
6323    }
6324
6325    /**
6326     * If the database version for this type of package (internal storage or
6327     * external storage) is less than the version where package signatures
6328     * were updated, return true.
6329     */
6330    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6331        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6332        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6333    }
6334
6335    /**
6336     * Used for backward compatibility to make sure any packages with
6337     * certificate chains get upgraded to the new style. {@code existingSigs}
6338     * will be in the old format (since they were stored on disk from before the
6339     * system upgrade) and {@code scannedSigs} will be in the newer format.
6340     */
6341    private int compareSignaturesCompat(PackageSignatures existingSigs,
6342            PackageParser.Package scannedPkg) {
6343        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6344            return PackageManager.SIGNATURE_NO_MATCH;
6345        }
6346
6347        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6348        for (Signature sig : existingSigs.mSignatures) {
6349            existingSet.add(sig);
6350        }
6351        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6352        for (Signature sig : scannedPkg.mSignatures) {
6353            try {
6354                Signature[] chainSignatures = sig.getChainSignatures();
6355                for (Signature chainSig : chainSignatures) {
6356                    scannedCompatSet.add(chainSig);
6357                }
6358            } catch (CertificateEncodingException e) {
6359                scannedCompatSet.add(sig);
6360            }
6361        }
6362        /*
6363         * Make sure the expanded scanned set contains all signatures in the
6364         * existing one.
6365         */
6366        if (scannedCompatSet.equals(existingSet)) {
6367            // Migrate the old signatures to the new scheme.
6368            existingSigs.assignSignatures(scannedPkg.mSignatures);
6369            // The new KeySets will be re-added later in the scanning process.
6370            synchronized (mPackages) {
6371                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6372            }
6373            return PackageManager.SIGNATURE_MATCH;
6374        }
6375        return PackageManager.SIGNATURE_NO_MATCH;
6376    }
6377
6378    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6379        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6380        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6381    }
6382
6383    private int compareSignaturesRecover(PackageSignatures existingSigs,
6384            PackageParser.Package scannedPkg) {
6385        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6386            return PackageManager.SIGNATURE_NO_MATCH;
6387        }
6388
6389        String msg = null;
6390        try {
6391            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6392                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6393                        + scannedPkg.packageName);
6394                return PackageManager.SIGNATURE_MATCH;
6395            }
6396        } catch (CertificateException e) {
6397            msg = e.getMessage();
6398        }
6399
6400        logCriticalInfo(Log.INFO,
6401                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6402        return PackageManager.SIGNATURE_NO_MATCH;
6403    }
6404
6405    @Override
6406    public List<String> getAllPackages() {
6407        final int callingUid = Binder.getCallingUid();
6408        final int callingUserId = UserHandle.getUserId(callingUid);
6409        synchronized (mPackages) {
6410            if (canViewInstantApps(callingUid, callingUserId)) {
6411                return new ArrayList<String>(mPackages.keySet());
6412            }
6413            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6414            final List<String> result = new ArrayList<>();
6415            if (instantAppPkgName != null) {
6416                // caller is an instant application; filter unexposed applications
6417                for (PackageParser.Package pkg : mPackages.values()) {
6418                    if (!pkg.visibleToInstantApps) {
6419                        continue;
6420                    }
6421                    result.add(pkg.packageName);
6422                }
6423            } else {
6424                // caller is a normal application; filter instant applications
6425                for (PackageParser.Package pkg : mPackages.values()) {
6426                    final PackageSetting ps =
6427                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6428                    if (ps != null
6429                            && ps.getInstantApp(callingUserId)
6430                            && !mInstantAppRegistry.isInstantAccessGranted(
6431                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6432                        continue;
6433                    }
6434                    result.add(pkg.packageName);
6435                }
6436            }
6437            return result;
6438        }
6439    }
6440
6441    @Override
6442    public String[] getPackagesForUid(int uid) {
6443        final int callingUid = Binder.getCallingUid();
6444        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6445        final int userId = UserHandle.getUserId(uid);
6446        uid = UserHandle.getAppId(uid);
6447        // reader
6448        synchronized (mPackages) {
6449            Object obj = mSettings.getUserIdLPr(uid);
6450            if (obj instanceof SharedUserSetting) {
6451                if (isCallerInstantApp) {
6452                    return null;
6453                }
6454                final SharedUserSetting sus = (SharedUserSetting) obj;
6455                final int N = sus.packages.size();
6456                String[] res = new String[N];
6457                final Iterator<PackageSetting> it = sus.packages.iterator();
6458                int i = 0;
6459                while (it.hasNext()) {
6460                    PackageSetting ps = it.next();
6461                    if (ps.getInstalled(userId)) {
6462                        res[i++] = ps.name;
6463                    } else {
6464                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6465                    }
6466                }
6467                return res;
6468            } else if (obj instanceof PackageSetting) {
6469                final PackageSetting ps = (PackageSetting) obj;
6470                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6471                    return new String[]{ps.name};
6472                }
6473            }
6474        }
6475        return null;
6476    }
6477
6478    @Override
6479    public String getNameForUid(int uid) {
6480        final int callingUid = Binder.getCallingUid();
6481        if (getInstantAppPackageName(callingUid) != null) {
6482            return null;
6483        }
6484        synchronized (mPackages) {
6485            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6486            if (obj instanceof SharedUserSetting) {
6487                final SharedUserSetting sus = (SharedUserSetting) obj;
6488                return sus.name + ":" + sus.userId;
6489            } else if (obj instanceof PackageSetting) {
6490                final PackageSetting ps = (PackageSetting) obj;
6491                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6492                    return null;
6493                }
6494                return ps.name;
6495            }
6496            return null;
6497        }
6498    }
6499
6500    @Override
6501    public String[] getNamesForUids(int[] uids) {
6502        if (uids == null || uids.length == 0) {
6503            return null;
6504        }
6505        final int callingUid = Binder.getCallingUid();
6506        if (getInstantAppPackageName(callingUid) != null) {
6507            return null;
6508        }
6509        final String[] names = new String[uids.length];
6510        synchronized (mPackages) {
6511            for (int i = uids.length - 1; i >= 0; i--) {
6512                final int uid = uids[i];
6513                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6514                if (obj instanceof SharedUserSetting) {
6515                    final SharedUserSetting sus = (SharedUserSetting) obj;
6516                    names[i] = "shared:" + sus.name;
6517                } else if (obj instanceof PackageSetting) {
6518                    final PackageSetting ps = (PackageSetting) obj;
6519                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6520                        names[i] = null;
6521                    } else {
6522                        names[i] = ps.name;
6523                    }
6524                } else {
6525                    names[i] = null;
6526                }
6527            }
6528        }
6529        return names;
6530    }
6531
6532    @Override
6533    public int getUidForSharedUser(String sharedUserName) {
6534        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6535            return -1;
6536        }
6537        if (sharedUserName == null) {
6538            return -1;
6539        }
6540        // reader
6541        synchronized (mPackages) {
6542            SharedUserSetting suid;
6543            try {
6544                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6545                if (suid != null) {
6546                    return suid.userId;
6547                }
6548            } catch (PackageManagerException ignore) {
6549                // can't happen, but, still need to catch it
6550            }
6551            return -1;
6552        }
6553    }
6554
6555    @Override
6556    public int getFlagsForUid(int uid) {
6557        final int callingUid = Binder.getCallingUid();
6558        if (getInstantAppPackageName(callingUid) != null) {
6559            return 0;
6560        }
6561        synchronized (mPackages) {
6562            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6563            if (obj instanceof SharedUserSetting) {
6564                final SharedUserSetting sus = (SharedUserSetting) obj;
6565                return sus.pkgFlags;
6566            } else if (obj instanceof PackageSetting) {
6567                final PackageSetting ps = (PackageSetting) obj;
6568                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6569                    return 0;
6570                }
6571                return ps.pkgFlags;
6572            }
6573        }
6574        return 0;
6575    }
6576
6577    @Override
6578    public int getPrivateFlagsForUid(int uid) {
6579        final int callingUid = Binder.getCallingUid();
6580        if (getInstantAppPackageName(callingUid) != null) {
6581            return 0;
6582        }
6583        synchronized (mPackages) {
6584            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6585            if (obj instanceof SharedUserSetting) {
6586                final SharedUserSetting sus = (SharedUserSetting) obj;
6587                return sus.pkgPrivateFlags;
6588            } else if (obj instanceof PackageSetting) {
6589                final PackageSetting ps = (PackageSetting) obj;
6590                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6591                    return 0;
6592                }
6593                return ps.pkgPrivateFlags;
6594            }
6595        }
6596        return 0;
6597    }
6598
6599    @Override
6600    public boolean isUidPrivileged(int uid) {
6601        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6602            return false;
6603        }
6604        uid = UserHandle.getAppId(uid);
6605        // reader
6606        synchronized (mPackages) {
6607            Object obj = mSettings.getUserIdLPr(uid);
6608            if (obj instanceof SharedUserSetting) {
6609                final SharedUserSetting sus = (SharedUserSetting) obj;
6610                final Iterator<PackageSetting> it = sus.packages.iterator();
6611                while (it.hasNext()) {
6612                    if (it.next().isPrivileged()) {
6613                        return true;
6614                    }
6615                }
6616            } else if (obj instanceof PackageSetting) {
6617                final PackageSetting ps = (PackageSetting) obj;
6618                return ps.isPrivileged();
6619            }
6620        }
6621        return false;
6622    }
6623
6624    @Override
6625    public String[] getAppOpPermissionPackages(String permissionName) {
6626        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6627            return null;
6628        }
6629        synchronized (mPackages) {
6630            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6631            if (pkgs == null) {
6632                return null;
6633            }
6634            return pkgs.toArray(new String[pkgs.size()]);
6635        }
6636    }
6637
6638    @Override
6639    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6640            int flags, int userId) {
6641        return resolveIntentInternal(
6642                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6643    }
6644
6645    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6646            int flags, int userId, boolean resolveForStart) {
6647        try {
6648            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6649
6650            if (!sUserManager.exists(userId)) return null;
6651            final int callingUid = Binder.getCallingUid();
6652            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6653            enforceCrossUserPermission(callingUid, userId,
6654                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6655
6656            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6657            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6658                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6659            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6660
6661            final ResolveInfo bestChoice =
6662                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6663            return bestChoice;
6664        } finally {
6665            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6666        }
6667    }
6668
6669    @Override
6670    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6671        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6672            throw new SecurityException(
6673                    "findPersistentPreferredActivity can only be run by the system");
6674        }
6675        if (!sUserManager.exists(userId)) {
6676            return null;
6677        }
6678        final int callingUid = Binder.getCallingUid();
6679        intent = updateIntentForResolve(intent);
6680        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6681        final int flags = updateFlagsForResolve(
6682                0, userId, intent, callingUid, false /*includeInstantApps*/);
6683        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6684                userId);
6685        synchronized (mPackages) {
6686            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6687                    userId);
6688        }
6689    }
6690
6691    @Override
6692    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6693            IntentFilter filter, int match, ComponentName activity) {
6694        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6695            return;
6696        }
6697        final int userId = UserHandle.getCallingUserId();
6698        if (DEBUG_PREFERRED) {
6699            Log.v(TAG, "setLastChosenActivity intent=" + intent
6700                + " resolvedType=" + resolvedType
6701                + " flags=" + flags
6702                + " filter=" + filter
6703                + " match=" + match
6704                + " activity=" + activity);
6705            filter.dump(new PrintStreamPrinter(System.out), "    ");
6706        }
6707        intent.setComponent(null);
6708        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6709                userId);
6710        // Find any earlier preferred or last chosen entries and nuke them
6711        findPreferredActivity(intent, resolvedType,
6712                flags, query, 0, false, true, false, userId);
6713        // Add the new activity as the last chosen for this filter
6714        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6715                "Setting last chosen");
6716    }
6717
6718    @Override
6719    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6720        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6721            return null;
6722        }
6723        final int userId = UserHandle.getCallingUserId();
6724        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6725        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6726                userId);
6727        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6728                false, false, false, userId);
6729    }
6730
6731    /**
6732     * Returns whether or not instant apps have been disabled remotely.
6733     */
6734    private boolean isEphemeralDisabled() {
6735        return mEphemeralAppsDisabled;
6736    }
6737
6738    private boolean isInstantAppAllowed(
6739            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6740            boolean skipPackageCheck) {
6741        if (mInstantAppResolverConnection == null) {
6742            return false;
6743        }
6744        if (mInstantAppInstallerActivity == null) {
6745            return false;
6746        }
6747        if (intent.getComponent() != null) {
6748            return false;
6749        }
6750        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6751            return false;
6752        }
6753        if (!skipPackageCheck && intent.getPackage() != null) {
6754            return false;
6755        }
6756        final boolean isWebUri = hasWebURI(intent);
6757        if (!isWebUri || intent.getData().getHost() == null) {
6758            return false;
6759        }
6760        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6761        // Or if there's already an ephemeral app installed that handles the action
6762        synchronized (mPackages) {
6763            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6764            for (int n = 0; n < count; n++) {
6765                final ResolveInfo info = resolvedActivities.get(n);
6766                final String packageName = info.activityInfo.packageName;
6767                final PackageSetting ps = mSettings.mPackages.get(packageName);
6768                if (ps != null) {
6769                    // only check domain verification status if the app is not a browser
6770                    if (!info.handleAllWebDataURI) {
6771                        // Try to get the status from User settings first
6772                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6773                        final int status = (int) (packedStatus >> 32);
6774                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6775                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6776                            if (DEBUG_EPHEMERAL) {
6777                                Slog.v(TAG, "DENY instant app;"
6778                                    + " pkg: " + packageName + ", status: " + status);
6779                            }
6780                            return false;
6781                        }
6782                    }
6783                    if (ps.getInstantApp(userId)) {
6784                        if (DEBUG_EPHEMERAL) {
6785                            Slog.v(TAG, "DENY instant app installed;"
6786                                    + " pkg: " + packageName);
6787                        }
6788                        return false;
6789                    }
6790                }
6791            }
6792        }
6793        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6794        return true;
6795    }
6796
6797    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6798            Intent origIntent, String resolvedType, String callingPackage,
6799            Bundle verificationBundle, int userId) {
6800        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6801                new InstantAppRequest(responseObj, origIntent, resolvedType,
6802                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6803        mHandler.sendMessage(msg);
6804    }
6805
6806    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6807            int flags, List<ResolveInfo> query, int userId) {
6808        if (query != null) {
6809            final int N = query.size();
6810            if (N == 1) {
6811                return query.get(0);
6812            } else if (N > 1) {
6813                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6814                // If there is more than one activity with the same priority,
6815                // then let the user decide between them.
6816                ResolveInfo r0 = query.get(0);
6817                ResolveInfo r1 = query.get(1);
6818                if (DEBUG_INTENT_MATCHING || debug) {
6819                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6820                            + r1.activityInfo.name + "=" + r1.priority);
6821                }
6822                // If the first activity has a higher priority, or a different
6823                // default, then it is always desirable to pick it.
6824                if (r0.priority != r1.priority
6825                        || r0.preferredOrder != r1.preferredOrder
6826                        || r0.isDefault != r1.isDefault) {
6827                    return query.get(0);
6828                }
6829                // If we have saved a preference for a preferred activity for
6830                // this Intent, use that.
6831                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6832                        flags, query, r0.priority, true, false, debug, userId);
6833                if (ri != null) {
6834                    return ri;
6835                }
6836                // If we have an ephemeral app, use it
6837                for (int i = 0; i < N; i++) {
6838                    ri = query.get(i);
6839                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6840                        final String packageName = ri.activityInfo.packageName;
6841                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6842                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6843                        final int status = (int)(packedStatus >> 32);
6844                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6845                            return ri;
6846                        }
6847                    }
6848                }
6849                ri = new ResolveInfo(mResolveInfo);
6850                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6851                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6852                // If all of the options come from the same package, show the application's
6853                // label and icon instead of the generic resolver's.
6854                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6855                // and then throw away the ResolveInfo itself, meaning that the caller loses
6856                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6857                // a fallback for this case; we only set the target package's resources on
6858                // the ResolveInfo, not the ActivityInfo.
6859                final String intentPackage = intent.getPackage();
6860                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6861                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6862                    ri.resolvePackageName = intentPackage;
6863                    if (userNeedsBadging(userId)) {
6864                        ri.noResourceId = true;
6865                    } else {
6866                        ri.icon = appi.icon;
6867                    }
6868                    ri.iconResourceId = appi.icon;
6869                    ri.labelRes = appi.labelRes;
6870                }
6871                ri.activityInfo.applicationInfo = new ApplicationInfo(
6872                        ri.activityInfo.applicationInfo);
6873                if (userId != 0) {
6874                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6875                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6876                }
6877                // Make sure that the resolver is displayable in car mode
6878                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6879                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6880                return ri;
6881            }
6882        }
6883        return null;
6884    }
6885
6886    /**
6887     * Return true if the given list is not empty and all of its contents have
6888     * an activityInfo with the given package name.
6889     */
6890    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6891        if (ArrayUtils.isEmpty(list)) {
6892            return false;
6893        }
6894        for (int i = 0, N = list.size(); i < N; i++) {
6895            final ResolveInfo ri = list.get(i);
6896            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6897            if (ai == null || !packageName.equals(ai.packageName)) {
6898                return false;
6899            }
6900        }
6901        return true;
6902    }
6903
6904    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6905            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6906        final int N = query.size();
6907        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6908                .get(userId);
6909        // Get the list of persistent preferred activities that handle the intent
6910        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6911        List<PersistentPreferredActivity> pprefs = ppir != null
6912                ? ppir.queryIntent(intent, resolvedType,
6913                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6914                        userId)
6915                : null;
6916        if (pprefs != null && pprefs.size() > 0) {
6917            final int M = pprefs.size();
6918            for (int i=0; i<M; i++) {
6919                final PersistentPreferredActivity ppa = pprefs.get(i);
6920                if (DEBUG_PREFERRED || debug) {
6921                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6922                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6923                            + "\n  component=" + ppa.mComponent);
6924                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6925                }
6926                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6927                        flags | MATCH_DISABLED_COMPONENTS, userId);
6928                if (DEBUG_PREFERRED || debug) {
6929                    Slog.v(TAG, "Found persistent preferred activity:");
6930                    if (ai != null) {
6931                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6932                    } else {
6933                        Slog.v(TAG, "  null");
6934                    }
6935                }
6936                if (ai == null) {
6937                    // This previously registered persistent preferred activity
6938                    // component is no longer known. Ignore it and do NOT remove it.
6939                    continue;
6940                }
6941                for (int j=0; j<N; j++) {
6942                    final ResolveInfo ri = query.get(j);
6943                    if (!ri.activityInfo.applicationInfo.packageName
6944                            .equals(ai.applicationInfo.packageName)) {
6945                        continue;
6946                    }
6947                    if (!ri.activityInfo.name.equals(ai.name)) {
6948                        continue;
6949                    }
6950                    //  Found a persistent preference that can handle the intent.
6951                    if (DEBUG_PREFERRED || debug) {
6952                        Slog.v(TAG, "Returning persistent preferred activity: " +
6953                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6954                    }
6955                    return ri;
6956                }
6957            }
6958        }
6959        return null;
6960    }
6961
6962    // TODO: handle preferred activities missing while user has amnesia
6963    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6964            List<ResolveInfo> query, int priority, boolean always,
6965            boolean removeMatches, boolean debug, int userId) {
6966        if (!sUserManager.exists(userId)) return null;
6967        final int callingUid = Binder.getCallingUid();
6968        flags = updateFlagsForResolve(
6969                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6970        intent = updateIntentForResolve(intent);
6971        // writer
6972        synchronized (mPackages) {
6973            // Try to find a matching persistent preferred activity.
6974            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6975                    debug, userId);
6976
6977            // If a persistent preferred activity matched, use it.
6978            if (pri != null) {
6979                return pri;
6980            }
6981
6982            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6983            // Get the list of preferred activities that handle the intent
6984            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6985            List<PreferredActivity> prefs = pir != null
6986                    ? pir.queryIntent(intent, resolvedType,
6987                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6988                            userId)
6989                    : null;
6990            if (prefs != null && prefs.size() > 0) {
6991                boolean changed = false;
6992                try {
6993                    // First figure out how good the original match set is.
6994                    // We will only allow preferred activities that came
6995                    // from the same match quality.
6996                    int match = 0;
6997
6998                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6999
7000                    final int N = query.size();
7001                    for (int j=0; j<N; j++) {
7002                        final ResolveInfo ri = query.get(j);
7003                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
7004                                + ": 0x" + Integer.toHexString(match));
7005                        if (ri.match > match) {
7006                            match = ri.match;
7007                        }
7008                    }
7009
7010                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
7011                            + Integer.toHexString(match));
7012
7013                    match &= IntentFilter.MATCH_CATEGORY_MASK;
7014                    final int M = prefs.size();
7015                    for (int i=0; i<M; i++) {
7016                        final PreferredActivity pa = prefs.get(i);
7017                        if (DEBUG_PREFERRED || debug) {
7018                            Slog.v(TAG, "Checking PreferredActivity ds="
7019                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
7020                                    + "\n  component=" + pa.mPref.mComponent);
7021                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7022                        }
7023                        if (pa.mPref.mMatch != match) {
7024                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
7025                                    + Integer.toHexString(pa.mPref.mMatch));
7026                            continue;
7027                        }
7028                        // If it's not an "always" type preferred activity and that's what we're
7029                        // looking for, skip it.
7030                        if (always && !pa.mPref.mAlways) {
7031                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7032                            continue;
7033                        }
7034                        final ActivityInfo ai = getActivityInfo(
7035                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7036                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7037                                userId);
7038                        if (DEBUG_PREFERRED || debug) {
7039                            Slog.v(TAG, "Found preferred activity:");
7040                            if (ai != null) {
7041                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7042                            } else {
7043                                Slog.v(TAG, "  null");
7044                            }
7045                        }
7046                        if (ai == null) {
7047                            // This previously registered preferred activity
7048                            // component is no longer known.  Most likely an update
7049                            // to the app was installed and in the new version this
7050                            // component no longer exists.  Clean it up by removing
7051                            // it from the preferred activities list, and skip it.
7052                            Slog.w(TAG, "Removing dangling preferred activity: "
7053                                    + pa.mPref.mComponent);
7054                            pir.removeFilter(pa);
7055                            changed = true;
7056                            continue;
7057                        }
7058                        for (int j=0; j<N; j++) {
7059                            final ResolveInfo ri = query.get(j);
7060                            if (!ri.activityInfo.applicationInfo.packageName
7061                                    .equals(ai.applicationInfo.packageName)) {
7062                                continue;
7063                            }
7064                            if (!ri.activityInfo.name.equals(ai.name)) {
7065                                continue;
7066                            }
7067
7068                            if (removeMatches) {
7069                                pir.removeFilter(pa);
7070                                changed = true;
7071                                if (DEBUG_PREFERRED) {
7072                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7073                                }
7074                                break;
7075                            }
7076
7077                            // Okay we found a previously set preferred or last chosen app.
7078                            // If the result set is different from when this
7079                            // was created, and is not a subset of the preferred set, we need to
7080                            // clear it and re-ask the user their preference, if we're looking for
7081                            // an "always" type entry.
7082                            if (always && !pa.mPref.sameSet(query)) {
7083                                if (pa.mPref.isSuperset(query)) {
7084                                    // some components of the set are no longer present in
7085                                    // the query, but the preferred activity can still be reused
7086                                    if (DEBUG_PREFERRED) {
7087                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7088                                                + " still valid as only non-preferred components"
7089                                                + " were removed for " + intent + " type "
7090                                                + resolvedType);
7091                                    }
7092                                    // remove obsolete components and re-add the up-to-date filter
7093                                    PreferredActivity freshPa = new PreferredActivity(pa,
7094                                            pa.mPref.mMatch,
7095                                            pa.mPref.discardObsoleteComponents(query),
7096                                            pa.mPref.mComponent,
7097                                            pa.mPref.mAlways);
7098                                    pir.removeFilter(pa);
7099                                    pir.addFilter(freshPa);
7100                                    changed = true;
7101                                } else {
7102                                    Slog.i(TAG,
7103                                            "Result set changed, dropping preferred activity for "
7104                                                    + intent + " type " + resolvedType);
7105                                    if (DEBUG_PREFERRED) {
7106                                        Slog.v(TAG, "Removing preferred activity since set changed "
7107                                                + pa.mPref.mComponent);
7108                                    }
7109                                    pir.removeFilter(pa);
7110                                    // Re-add the filter as a "last chosen" entry (!always)
7111                                    PreferredActivity lastChosen = new PreferredActivity(
7112                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7113                                    pir.addFilter(lastChosen);
7114                                    changed = true;
7115                                    return null;
7116                                }
7117                            }
7118
7119                            // Yay! Either the set matched or we're looking for the last chosen
7120                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7121                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7122                            return ri;
7123                        }
7124                    }
7125                } finally {
7126                    if (changed) {
7127                        if (DEBUG_PREFERRED) {
7128                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7129                        }
7130                        scheduleWritePackageRestrictionsLocked(userId);
7131                    }
7132                }
7133            }
7134        }
7135        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7136        return null;
7137    }
7138
7139    /*
7140     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7141     */
7142    @Override
7143    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7144            int targetUserId) {
7145        mContext.enforceCallingOrSelfPermission(
7146                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7147        List<CrossProfileIntentFilter> matches =
7148                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7149        if (matches != null) {
7150            int size = matches.size();
7151            for (int i = 0; i < size; i++) {
7152                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7153            }
7154        }
7155        if (hasWebURI(intent)) {
7156            // cross-profile app linking works only towards the parent.
7157            final int callingUid = Binder.getCallingUid();
7158            final UserInfo parent = getProfileParent(sourceUserId);
7159            synchronized(mPackages) {
7160                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7161                        false /*includeInstantApps*/);
7162                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7163                        intent, resolvedType, flags, sourceUserId, parent.id);
7164                return xpDomainInfo != null;
7165            }
7166        }
7167        return false;
7168    }
7169
7170    private UserInfo getProfileParent(int userId) {
7171        final long identity = Binder.clearCallingIdentity();
7172        try {
7173            return sUserManager.getProfileParent(userId);
7174        } finally {
7175            Binder.restoreCallingIdentity(identity);
7176        }
7177    }
7178
7179    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7180            String resolvedType, int userId) {
7181        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7182        if (resolver != null) {
7183            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7184        }
7185        return null;
7186    }
7187
7188    @Override
7189    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7190            String resolvedType, int flags, int userId) {
7191        try {
7192            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7193
7194            return new ParceledListSlice<>(
7195                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7196        } finally {
7197            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7198        }
7199    }
7200
7201    /**
7202     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7203     * instant, returns {@code null}.
7204     */
7205    private String getInstantAppPackageName(int callingUid) {
7206        synchronized (mPackages) {
7207            // If the caller is an isolated app use the owner's uid for the lookup.
7208            if (Process.isIsolated(callingUid)) {
7209                callingUid = mIsolatedOwners.get(callingUid);
7210            }
7211            final int appId = UserHandle.getAppId(callingUid);
7212            final Object obj = mSettings.getUserIdLPr(appId);
7213            if (obj instanceof PackageSetting) {
7214                final PackageSetting ps = (PackageSetting) obj;
7215                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7216                return isInstantApp ? ps.pkg.packageName : null;
7217            }
7218        }
7219        return null;
7220    }
7221
7222    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7223            String resolvedType, int flags, int userId) {
7224        return queryIntentActivitiesInternal(
7225                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7226                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7227    }
7228
7229    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7230            String resolvedType, int flags, int filterCallingUid, int userId,
7231            boolean resolveForStart, boolean allowDynamicSplits) {
7232        if (!sUserManager.exists(userId)) return Collections.emptyList();
7233        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7234        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7235                false /* requireFullPermission */, false /* checkShell */,
7236                "query intent activities");
7237        final String pkgName = intent.getPackage();
7238        ComponentName comp = intent.getComponent();
7239        if (comp == null) {
7240            if (intent.getSelector() != null) {
7241                intent = intent.getSelector();
7242                comp = intent.getComponent();
7243            }
7244        }
7245
7246        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7247                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7248        if (comp != null) {
7249            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7250            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7251            if (ai != null) {
7252                // When specifying an explicit component, we prevent the activity from being
7253                // used when either 1) the calling package is normal and the activity is within
7254                // an ephemeral application or 2) the calling package is ephemeral and the
7255                // activity is not visible to ephemeral applications.
7256                final boolean matchInstantApp =
7257                        (flags & PackageManager.MATCH_INSTANT) != 0;
7258                final boolean matchVisibleToInstantAppOnly =
7259                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7260                final boolean matchExplicitlyVisibleOnly =
7261                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7262                final boolean isCallerInstantApp =
7263                        instantAppPkgName != null;
7264                final boolean isTargetSameInstantApp =
7265                        comp.getPackageName().equals(instantAppPkgName);
7266                final boolean isTargetInstantApp =
7267                        (ai.applicationInfo.privateFlags
7268                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7269                final boolean isTargetVisibleToInstantApp =
7270                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7271                final boolean isTargetExplicitlyVisibleToInstantApp =
7272                        isTargetVisibleToInstantApp
7273                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7274                final boolean isTargetHiddenFromInstantApp =
7275                        !isTargetVisibleToInstantApp
7276                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7277                final boolean blockResolution =
7278                        !isTargetSameInstantApp
7279                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7280                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7281                                        && isTargetHiddenFromInstantApp));
7282                if (!blockResolution) {
7283                    final ResolveInfo ri = new ResolveInfo();
7284                    ri.activityInfo = ai;
7285                    list.add(ri);
7286                }
7287            }
7288            return applyPostResolutionFilter(
7289                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7290        }
7291
7292        // reader
7293        boolean sortResult = false;
7294        boolean addEphemeral = false;
7295        List<ResolveInfo> result;
7296        final boolean ephemeralDisabled = isEphemeralDisabled();
7297        synchronized (mPackages) {
7298            if (pkgName == null) {
7299                List<CrossProfileIntentFilter> matchingFilters =
7300                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7301                // Check for results that need to skip the current profile.
7302                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7303                        resolvedType, flags, userId);
7304                if (xpResolveInfo != null) {
7305                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7306                    xpResult.add(xpResolveInfo);
7307                    return applyPostResolutionFilter(
7308                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7309                            allowDynamicSplits, filterCallingUid, userId);
7310                }
7311
7312                // Check for results in the current profile.
7313                result = filterIfNotSystemUser(mActivities.queryIntent(
7314                        intent, resolvedType, flags, userId), userId);
7315                addEphemeral = !ephemeralDisabled
7316                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7317                // Check for cross profile results.
7318                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7319                xpResolveInfo = queryCrossProfileIntents(
7320                        matchingFilters, intent, resolvedType, flags, userId,
7321                        hasNonNegativePriorityResult);
7322                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7323                    boolean isVisibleToUser = filterIfNotSystemUser(
7324                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7325                    if (isVisibleToUser) {
7326                        result.add(xpResolveInfo);
7327                        sortResult = true;
7328                    }
7329                }
7330                if (hasWebURI(intent)) {
7331                    CrossProfileDomainInfo xpDomainInfo = null;
7332                    final UserInfo parent = getProfileParent(userId);
7333                    if (parent != null) {
7334                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7335                                flags, userId, parent.id);
7336                    }
7337                    if (xpDomainInfo != null) {
7338                        if (xpResolveInfo != null) {
7339                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7340                            // in the result.
7341                            result.remove(xpResolveInfo);
7342                        }
7343                        if (result.size() == 0 && !addEphemeral) {
7344                            // No result in current profile, but found candidate in parent user.
7345                            // And we are not going to add emphemeral app, so we can return the
7346                            // result straight away.
7347                            result.add(xpDomainInfo.resolveInfo);
7348                            return applyPostResolutionFilter(result, instantAppPkgName,
7349                                    allowDynamicSplits, filterCallingUid, userId);
7350                        }
7351                    } else if (result.size() <= 1 && !addEphemeral) {
7352                        // No result in parent user and <= 1 result in current profile, and we
7353                        // are not going to add emphemeral app, so we can return the result without
7354                        // further processing.
7355                        return applyPostResolutionFilter(result, instantAppPkgName,
7356                                allowDynamicSplits, filterCallingUid, userId);
7357                    }
7358                    // We have more than one candidate (combining results from current and parent
7359                    // profile), so we need filtering and sorting.
7360                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7361                            intent, flags, result, xpDomainInfo, userId);
7362                    sortResult = true;
7363                }
7364            } else {
7365                final PackageParser.Package pkg = mPackages.get(pkgName);
7366                result = null;
7367                if (pkg != null) {
7368                    result = filterIfNotSystemUser(
7369                            mActivities.queryIntentForPackage(
7370                                    intent, resolvedType, flags, pkg.activities, userId),
7371                            userId);
7372                }
7373                if (result == null || result.size() == 0) {
7374                    // the caller wants to resolve for a particular package; however, there
7375                    // were no installed results, so, try to find an ephemeral result
7376                    addEphemeral = !ephemeralDisabled
7377                            && isInstantAppAllowed(
7378                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7379                    if (result == null) {
7380                        result = new ArrayList<>();
7381                    }
7382                }
7383            }
7384        }
7385        if (addEphemeral) {
7386            result = maybeAddInstantAppInstaller(
7387                    result, intent, resolvedType, flags, userId, resolveForStart);
7388        }
7389        if (sortResult) {
7390            Collections.sort(result, mResolvePrioritySorter);
7391        }
7392        return applyPostResolutionFilter(
7393                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7394    }
7395
7396    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7397            String resolvedType, int flags, int userId, boolean resolveForStart) {
7398        // first, check to see if we've got an instant app already installed
7399        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7400        ResolveInfo localInstantApp = null;
7401        boolean blockResolution = false;
7402        if (!alreadyResolvedLocally) {
7403            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7404                    flags
7405                        | PackageManager.GET_RESOLVED_FILTER
7406                        | PackageManager.MATCH_INSTANT
7407                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7408                    userId);
7409            for (int i = instantApps.size() - 1; i >= 0; --i) {
7410                final ResolveInfo info = instantApps.get(i);
7411                final String packageName = info.activityInfo.packageName;
7412                final PackageSetting ps = mSettings.mPackages.get(packageName);
7413                if (ps.getInstantApp(userId)) {
7414                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7415                    final int status = (int)(packedStatus >> 32);
7416                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7417                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7418                        // there's a local instant application installed, but, the user has
7419                        // chosen to never use it; skip resolution and don't acknowledge
7420                        // an instant application is even available
7421                        if (DEBUG_EPHEMERAL) {
7422                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7423                        }
7424                        blockResolution = true;
7425                        break;
7426                    } else {
7427                        // we have a locally installed instant application; skip resolution
7428                        // but acknowledge there's an instant application available
7429                        if (DEBUG_EPHEMERAL) {
7430                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7431                        }
7432                        localInstantApp = info;
7433                        break;
7434                    }
7435                }
7436            }
7437        }
7438        // no app installed, let's see if one's available
7439        AuxiliaryResolveInfo auxiliaryResponse = null;
7440        if (!blockResolution) {
7441            if (localInstantApp == null) {
7442                // we don't have an instant app locally, resolve externally
7443                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7444                final InstantAppRequest requestObject = new InstantAppRequest(
7445                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7446                        null /*callingPackage*/, userId, null /*verificationBundle*/,
7447                        resolveForStart);
7448                auxiliaryResponse =
7449                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7450                                mContext, mInstantAppResolverConnection, requestObject);
7451                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7452            } else {
7453                // we have an instant application locally, but, we can't admit that since
7454                // callers shouldn't be able to determine prior browsing. create a dummy
7455                // auxiliary response so the downstream code behaves as if there's an
7456                // instant application available externally. when it comes time to start
7457                // the instant application, we'll do the right thing.
7458                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7459                auxiliaryResponse = new AuxiliaryResolveInfo(
7460                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7461                        ai.versionCode, null /*failureIntent*/);
7462            }
7463        }
7464        if (auxiliaryResponse != null) {
7465            if (DEBUG_EPHEMERAL) {
7466                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7467            }
7468            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7469            final PackageSetting ps =
7470                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7471            if (ps != null) {
7472                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7473                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7474                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7475                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7476                // make sure this resolver is the default
7477                ephemeralInstaller.isDefault = true;
7478                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7479                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7480                // add a non-generic filter
7481                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7482                ephemeralInstaller.filter.addDataPath(
7483                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7484                ephemeralInstaller.isInstantAppAvailable = true;
7485                result.add(ephemeralInstaller);
7486            }
7487        }
7488        return result;
7489    }
7490
7491    private static class CrossProfileDomainInfo {
7492        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7493        ResolveInfo resolveInfo;
7494        /* Best domain verification status of the activities found in the other profile */
7495        int bestDomainVerificationStatus;
7496    }
7497
7498    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7499            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7500        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7501                sourceUserId)) {
7502            return null;
7503        }
7504        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7505                resolvedType, flags, parentUserId);
7506
7507        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7508            return null;
7509        }
7510        CrossProfileDomainInfo result = null;
7511        int size = resultTargetUser.size();
7512        for (int i = 0; i < size; i++) {
7513            ResolveInfo riTargetUser = resultTargetUser.get(i);
7514            // Intent filter verification is only for filters that specify a host. So don't return
7515            // those that handle all web uris.
7516            if (riTargetUser.handleAllWebDataURI) {
7517                continue;
7518            }
7519            String packageName = riTargetUser.activityInfo.packageName;
7520            PackageSetting ps = mSettings.mPackages.get(packageName);
7521            if (ps == null) {
7522                continue;
7523            }
7524            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7525            int status = (int)(verificationState >> 32);
7526            if (result == null) {
7527                result = new CrossProfileDomainInfo();
7528                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7529                        sourceUserId, parentUserId);
7530                result.bestDomainVerificationStatus = status;
7531            } else {
7532                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7533                        result.bestDomainVerificationStatus);
7534            }
7535        }
7536        // Don't consider matches with status NEVER across profiles.
7537        if (result != null && result.bestDomainVerificationStatus
7538                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7539            return null;
7540        }
7541        return result;
7542    }
7543
7544    /**
7545     * Verification statuses are ordered from the worse to the best, except for
7546     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7547     */
7548    private int bestDomainVerificationStatus(int status1, int status2) {
7549        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7550            return status2;
7551        }
7552        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7553            return status1;
7554        }
7555        return (int) MathUtils.max(status1, status2);
7556    }
7557
7558    private boolean isUserEnabled(int userId) {
7559        long callingId = Binder.clearCallingIdentity();
7560        try {
7561            UserInfo userInfo = sUserManager.getUserInfo(userId);
7562            return userInfo != null && userInfo.isEnabled();
7563        } finally {
7564            Binder.restoreCallingIdentity(callingId);
7565        }
7566    }
7567
7568    /**
7569     * Filter out activities with systemUserOnly flag set, when current user is not System.
7570     *
7571     * @return filtered list
7572     */
7573    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7574        if (userId == UserHandle.USER_SYSTEM) {
7575            return resolveInfos;
7576        }
7577        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7578            ResolveInfo info = resolveInfos.get(i);
7579            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7580                resolveInfos.remove(i);
7581            }
7582        }
7583        return resolveInfos;
7584    }
7585
7586    /**
7587     * Filters out ephemeral activities.
7588     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7589     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7590     *
7591     * @param resolveInfos The pre-filtered list of resolved activities
7592     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7593     *          is performed.
7594     * @return A filtered list of resolved activities.
7595     */
7596    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7597            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7598        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7599            final ResolveInfo info = resolveInfos.get(i);
7600            // allow activities that are defined in the provided package
7601            if (allowDynamicSplits
7602                    && info.activityInfo.splitName != null
7603                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7604                            info.activityInfo.splitName)) {
7605                // requested activity is defined in a split that hasn't been installed yet.
7606                // add the installer to the resolve list
7607                if (DEBUG_INSTALL) {
7608                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7609                }
7610                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7611                final ComponentName installFailureActivity = findInstallFailureActivity(
7612                        info.activityInfo.packageName,  filterCallingUid, userId);
7613                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7614                        info.activityInfo.packageName, info.activityInfo.splitName,
7615                        installFailureActivity,
7616                        info.activityInfo.applicationInfo.versionCode,
7617                        null /*failureIntent*/);
7618                // make sure this resolver is the default
7619                installerInfo.isDefault = true;
7620                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7621                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7622                // add a non-generic filter
7623                installerInfo.filter = new IntentFilter();
7624                // load resources from the correct package
7625                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7626                resolveInfos.set(i, installerInfo);
7627                continue;
7628            }
7629            // caller is a full app, don't need to apply any other filtering
7630            if (ephemeralPkgName == null) {
7631                continue;
7632            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7633                // caller is same app; don't need to apply any other filtering
7634                continue;
7635            }
7636            // allow activities that have been explicitly exposed to ephemeral apps
7637            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7638            if (!isEphemeralApp
7639                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7640                continue;
7641            }
7642            resolveInfos.remove(i);
7643        }
7644        return resolveInfos;
7645    }
7646
7647    /**
7648     * Returns the activity component that can handle install failures.
7649     * <p>By default, the instant application installer handles failures. However, an
7650     * application may want to handle failures on its own. Applications do this by
7651     * creating an activity with an intent filter that handles the action
7652     * {@link Intent#ACTION_INSTALL_FAILURE}.
7653     */
7654    private @Nullable ComponentName findInstallFailureActivity(
7655            String packageName, int filterCallingUid, int userId) {
7656        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7657        failureActivityIntent.setPackage(packageName);
7658        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7659        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7660                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7661                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7662        final int NR = result.size();
7663        if (NR > 0) {
7664            for (int i = 0; i < NR; i++) {
7665                final ResolveInfo info = result.get(i);
7666                if (info.activityInfo.splitName != null) {
7667                    continue;
7668                }
7669                return new ComponentName(packageName, info.activityInfo.name);
7670            }
7671        }
7672        return null;
7673    }
7674
7675    /**
7676     * @param resolveInfos list of resolve infos in descending priority order
7677     * @return if the list contains a resolve info with non-negative priority
7678     */
7679    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7680        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7681    }
7682
7683    private static boolean hasWebURI(Intent intent) {
7684        if (intent.getData() == null) {
7685            return false;
7686        }
7687        final String scheme = intent.getScheme();
7688        if (TextUtils.isEmpty(scheme)) {
7689            return false;
7690        }
7691        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7692    }
7693
7694    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7695            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7696            int userId) {
7697        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7698
7699        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7700            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7701                    candidates.size());
7702        }
7703
7704        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7705        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7706        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7707        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7708        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7709        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7710
7711        synchronized (mPackages) {
7712            final int count = candidates.size();
7713            // First, try to use linked apps. Partition the candidates into four lists:
7714            // one for the final results, one for the "do not use ever", one for "undefined status"
7715            // and finally one for "browser app type".
7716            for (int n=0; n<count; n++) {
7717                ResolveInfo info = candidates.get(n);
7718                String packageName = info.activityInfo.packageName;
7719                PackageSetting ps = mSettings.mPackages.get(packageName);
7720                if (ps != null) {
7721                    // Add to the special match all list (Browser use case)
7722                    if (info.handleAllWebDataURI) {
7723                        matchAllList.add(info);
7724                        continue;
7725                    }
7726                    // Try to get the status from User settings first
7727                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7728                    int status = (int)(packedStatus >> 32);
7729                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7730                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7731                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7732                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7733                                    + " : linkgen=" + linkGeneration);
7734                        }
7735                        // Use link-enabled generation as preferredOrder, i.e.
7736                        // prefer newly-enabled over earlier-enabled.
7737                        info.preferredOrder = linkGeneration;
7738                        alwaysList.add(info);
7739                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7740                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7741                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7742                        }
7743                        neverList.add(info);
7744                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7745                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7746                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7747                        }
7748                        alwaysAskList.add(info);
7749                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7750                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7751                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7752                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7753                        }
7754                        undefinedList.add(info);
7755                    }
7756                }
7757            }
7758
7759            // We'll want to include browser possibilities in a few cases
7760            boolean includeBrowser = false;
7761
7762            // First try to add the "always" resolution(s) for the current user, if any
7763            if (alwaysList.size() > 0) {
7764                result.addAll(alwaysList);
7765            } else {
7766                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7767                result.addAll(undefinedList);
7768                // Maybe add one for the other profile.
7769                if (xpDomainInfo != null && (
7770                        xpDomainInfo.bestDomainVerificationStatus
7771                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7772                    result.add(xpDomainInfo.resolveInfo);
7773                }
7774                includeBrowser = true;
7775            }
7776
7777            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7778            // If there were 'always' entries their preferred order has been set, so we also
7779            // back that off to make the alternatives equivalent
7780            if (alwaysAskList.size() > 0) {
7781                for (ResolveInfo i : result) {
7782                    i.preferredOrder = 0;
7783                }
7784                result.addAll(alwaysAskList);
7785                includeBrowser = true;
7786            }
7787
7788            if (includeBrowser) {
7789                // Also add browsers (all of them or only the default one)
7790                if (DEBUG_DOMAIN_VERIFICATION) {
7791                    Slog.v(TAG, "   ...including browsers in candidate set");
7792                }
7793                if ((matchFlags & MATCH_ALL) != 0) {
7794                    result.addAll(matchAllList);
7795                } else {
7796                    // Browser/generic handling case.  If there's a default browser, go straight
7797                    // to that (but only if there is no other higher-priority match).
7798                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7799                    int maxMatchPrio = 0;
7800                    ResolveInfo defaultBrowserMatch = null;
7801                    final int numCandidates = matchAllList.size();
7802                    for (int n = 0; n < numCandidates; n++) {
7803                        ResolveInfo info = matchAllList.get(n);
7804                        // track the highest overall match priority...
7805                        if (info.priority > maxMatchPrio) {
7806                            maxMatchPrio = info.priority;
7807                        }
7808                        // ...and the highest-priority default browser match
7809                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7810                            if (defaultBrowserMatch == null
7811                                    || (defaultBrowserMatch.priority < info.priority)) {
7812                                if (debug) {
7813                                    Slog.v(TAG, "Considering default browser match " + info);
7814                                }
7815                                defaultBrowserMatch = info;
7816                            }
7817                        }
7818                    }
7819                    if (defaultBrowserMatch != null
7820                            && defaultBrowserMatch.priority >= maxMatchPrio
7821                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7822                    {
7823                        if (debug) {
7824                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7825                        }
7826                        result.add(defaultBrowserMatch);
7827                    } else {
7828                        result.addAll(matchAllList);
7829                    }
7830                }
7831
7832                // If there is nothing selected, add all candidates and remove the ones that the user
7833                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7834                if (result.size() == 0) {
7835                    result.addAll(candidates);
7836                    result.removeAll(neverList);
7837                }
7838            }
7839        }
7840        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7841            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7842                    result.size());
7843            for (ResolveInfo info : result) {
7844                Slog.v(TAG, "  + " + info.activityInfo);
7845            }
7846        }
7847        return result;
7848    }
7849
7850    // Returns a packed value as a long:
7851    //
7852    // high 'int'-sized word: link status: undefined/ask/never/always.
7853    // low 'int'-sized word: relative priority among 'always' results.
7854    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7855        long result = ps.getDomainVerificationStatusForUser(userId);
7856        // if none available, get the master status
7857        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7858            if (ps.getIntentFilterVerificationInfo() != null) {
7859                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7860            }
7861        }
7862        return result;
7863    }
7864
7865    private ResolveInfo querySkipCurrentProfileIntents(
7866            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7867            int flags, int sourceUserId) {
7868        if (matchingFilters != null) {
7869            int size = matchingFilters.size();
7870            for (int i = 0; i < size; i ++) {
7871                CrossProfileIntentFilter filter = matchingFilters.get(i);
7872                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7873                    // Checking if there are activities in the target user that can handle the
7874                    // intent.
7875                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7876                            resolvedType, flags, sourceUserId);
7877                    if (resolveInfo != null) {
7878                        return resolveInfo;
7879                    }
7880                }
7881            }
7882        }
7883        return null;
7884    }
7885
7886    // Return matching ResolveInfo in target user if any.
7887    private ResolveInfo queryCrossProfileIntents(
7888            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7889            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7890        if (matchingFilters != null) {
7891            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7892            // match the same intent. For performance reasons, it is better not to
7893            // run queryIntent twice for the same userId
7894            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7895            int size = matchingFilters.size();
7896            for (int i = 0; i < size; i++) {
7897                CrossProfileIntentFilter filter = matchingFilters.get(i);
7898                int targetUserId = filter.getTargetUserId();
7899                boolean skipCurrentProfile =
7900                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7901                boolean skipCurrentProfileIfNoMatchFound =
7902                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7903                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7904                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7905                    // Checking if there are activities in the target user that can handle the
7906                    // intent.
7907                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7908                            resolvedType, flags, sourceUserId);
7909                    if (resolveInfo != null) return resolveInfo;
7910                    alreadyTriedUserIds.put(targetUserId, true);
7911                }
7912            }
7913        }
7914        return null;
7915    }
7916
7917    /**
7918     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7919     * will forward the intent to the filter's target user.
7920     * Otherwise, returns null.
7921     */
7922    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7923            String resolvedType, int flags, int sourceUserId) {
7924        int targetUserId = filter.getTargetUserId();
7925        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7926                resolvedType, flags, targetUserId);
7927        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7928            // If all the matches in the target profile are suspended, return null.
7929            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7930                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7931                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7932                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7933                            targetUserId);
7934                }
7935            }
7936        }
7937        return null;
7938    }
7939
7940    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7941            int sourceUserId, int targetUserId) {
7942        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7943        long ident = Binder.clearCallingIdentity();
7944        boolean targetIsProfile;
7945        try {
7946            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7947        } finally {
7948            Binder.restoreCallingIdentity(ident);
7949        }
7950        String className;
7951        if (targetIsProfile) {
7952            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7953        } else {
7954            className = FORWARD_INTENT_TO_PARENT;
7955        }
7956        ComponentName forwardingActivityComponentName = new ComponentName(
7957                mAndroidApplication.packageName, className);
7958        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7959                sourceUserId);
7960        if (!targetIsProfile) {
7961            forwardingActivityInfo.showUserIcon = targetUserId;
7962            forwardingResolveInfo.noResourceId = true;
7963        }
7964        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7965        forwardingResolveInfo.priority = 0;
7966        forwardingResolveInfo.preferredOrder = 0;
7967        forwardingResolveInfo.match = 0;
7968        forwardingResolveInfo.isDefault = true;
7969        forwardingResolveInfo.filter = filter;
7970        forwardingResolveInfo.targetUserId = targetUserId;
7971        return forwardingResolveInfo;
7972    }
7973
7974    @Override
7975    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7976            Intent[] specifics, String[] specificTypes, Intent intent,
7977            String resolvedType, int flags, int userId) {
7978        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7979                specificTypes, intent, resolvedType, flags, userId));
7980    }
7981
7982    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7983            Intent[] specifics, String[] specificTypes, Intent intent,
7984            String resolvedType, int flags, int userId) {
7985        if (!sUserManager.exists(userId)) return Collections.emptyList();
7986        final int callingUid = Binder.getCallingUid();
7987        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7988                false /*includeInstantApps*/);
7989        enforceCrossUserPermission(callingUid, userId,
7990                false /*requireFullPermission*/, false /*checkShell*/,
7991                "query intent activity options");
7992        final String resultsAction = intent.getAction();
7993
7994        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7995                | PackageManager.GET_RESOLVED_FILTER, userId);
7996
7997        if (DEBUG_INTENT_MATCHING) {
7998            Log.v(TAG, "Query " + intent + ": " + results);
7999        }
8000
8001        int specificsPos = 0;
8002        int N;
8003
8004        // todo: note that the algorithm used here is O(N^2).  This
8005        // isn't a problem in our current environment, but if we start running
8006        // into situations where we have more than 5 or 10 matches then this
8007        // should probably be changed to something smarter...
8008
8009        // First we go through and resolve each of the specific items
8010        // that were supplied, taking care of removing any corresponding
8011        // duplicate items in the generic resolve list.
8012        if (specifics != null) {
8013            for (int i=0; i<specifics.length; i++) {
8014                final Intent sintent = specifics[i];
8015                if (sintent == null) {
8016                    continue;
8017                }
8018
8019                if (DEBUG_INTENT_MATCHING) {
8020                    Log.v(TAG, "Specific #" + i + ": " + sintent);
8021                }
8022
8023                String action = sintent.getAction();
8024                if (resultsAction != null && resultsAction.equals(action)) {
8025                    // If this action was explicitly requested, then don't
8026                    // remove things that have it.
8027                    action = null;
8028                }
8029
8030                ResolveInfo ri = null;
8031                ActivityInfo ai = null;
8032
8033                ComponentName comp = sintent.getComponent();
8034                if (comp == null) {
8035                    ri = resolveIntent(
8036                        sintent,
8037                        specificTypes != null ? specificTypes[i] : null,
8038                            flags, userId);
8039                    if (ri == null) {
8040                        continue;
8041                    }
8042                    if (ri == mResolveInfo) {
8043                        // ACK!  Must do something better with this.
8044                    }
8045                    ai = ri.activityInfo;
8046                    comp = new ComponentName(ai.applicationInfo.packageName,
8047                            ai.name);
8048                } else {
8049                    ai = getActivityInfo(comp, flags, userId);
8050                    if (ai == null) {
8051                        continue;
8052                    }
8053                }
8054
8055                // Look for any generic query activities that are duplicates
8056                // of this specific one, and remove them from the results.
8057                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8058                N = results.size();
8059                int j;
8060                for (j=specificsPos; j<N; j++) {
8061                    ResolveInfo sri = results.get(j);
8062                    if ((sri.activityInfo.name.equals(comp.getClassName())
8063                            && sri.activityInfo.applicationInfo.packageName.equals(
8064                                    comp.getPackageName()))
8065                        || (action != null && sri.filter.matchAction(action))) {
8066                        results.remove(j);
8067                        if (DEBUG_INTENT_MATCHING) Log.v(
8068                            TAG, "Removing duplicate item from " + j
8069                            + " due to specific " + specificsPos);
8070                        if (ri == null) {
8071                            ri = sri;
8072                        }
8073                        j--;
8074                        N--;
8075                    }
8076                }
8077
8078                // Add this specific item to its proper place.
8079                if (ri == null) {
8080                    ri = new ResolveInfo();
8081                    ri.activityInfo = ai;
8082                }
8083                results.add(specificsPos, ri);
8084                ri.specificIndex = i;
8085                specificsPos++;
8086            }
8087        }
8088
8089        // Now we go through the remaining generic results and remove any
8090        // duplicate actions that are found here.
8091        N = results.size();
8092        for (int i=specificsPos; i<N-1; i++) {
8093            final ResolveInfo rii = results.get(i);
8094            if (rii.filter == null) {
8095                continue;
8096            }
8097
8098            // Iterate over all of the actions of this result's intent
8099            // filter...  typically this should be just one.
8100            final Iterator<String> it = rii.filter.actionsIterator();
8101            if (it == null) {
8102                continue;
8103            }
8104            while (it.hasNext()) {
8105                final String action = it.next();
8106                if (resultsAction != null && resultsAction.equals(action)) {
8107                    // If this action was explicitly requested, then don't
8108                    // remove things that have it.
8109                    continue;
8110                }
8111                for (int j=i+1; j<N; j++) {
8112                    final ResolveInfo rij = results.get(j);
8113                    if (rij.filter != null && rij.filter.hasAction(action)) {
8114                        results.remove(j);
8115                        if (DEBUG_INTENT_MATCHING) Log.v(
8116                            TAG, "Removing duplicate item from " + j
8117                            + " due to action " + action + " at " + i);
8118                        j--;
8119                        N--;
8120                    }
8121                }
8122            }
8123
8124            // If the caller didn't request filter information, drop it now
8125            // so we don't have to marshall/unmarshall it.
8126            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8127                rii.filter = null;
8128            }
8129        }
8130
8131        // Filter out the caller activity if so requested.
8132        if (caller != null) {
8133            N = results.size();
8134            for (int i=0; i<N; i++) {
8135                ActivityInfo ainfo = results.get(i).activityInfo;
8136                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8137                        && caller.getClassName().equals(ainfo.name)) {
8138                    results.remove(i);
8139                    break;
8140                }
8141            }
8142        }
8143
8144        // If the caller didn't request filter information,
8145        // drop them now so we don't have to
8146        // marshall/unmarshall it.
8147        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8148            N = results.size();
8149            for (int i=0; i<N; i++) {
8150                results.get(i).filter = null;
8151            }
8152        }
8153
8154        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8155        return results;
8156    }
8157
8158    @Override
8159    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8160            String resolvedType, int flags, int userId) {
8161        return new ParceledListSlice<>(
8162                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8163                        false /*allowDynamicSplits*/));
8164    }
8165
8166    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8167            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8168        if (!sUserManager.exists(userId)) return Collections.emptyList();
8169        final int callingUid = Binder.getCallingUid();
8170        enforceCrossUserPermission(callingUid, userId,
8171                false /*requireFullPermission*/, false /*checkShell*/,
8172                "query intent receivers");
8173        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8174        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8175                false /*includeInstantApps*/);
8176        ComponentName comp = intent.getComponent();
8177        if (comp == null) {
8178            if (intent.getSelector() != null) {
8179                intent = intent.getSelector();
8180                comp = intent.getComponent();
8181            }
8182        }
8183        if (comp != null) {
8184            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8185            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8186            if (ai != null) {
8187                // When specifying an explicit component, we prevent the activity from being
8188                // used when either 1) the calling package is normal and the activity is within
8189                // an instant application or 2) the calling package is ephemeral and the
8190                // activity is not visible to instant applications.
8191                final boolean matchInstantApp =
8192                        (flags & PackageManager.MATCH_INSTANT) != 0;
8193                final boolean matchVisibleToInstantAppOnly =
8194                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8195                final boolean matchExplicitlyVisibleOnly =
8196                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8197                final boolean isCallerInstantApp =
8198                        instantAppPkgName != null;
8199                final boolean isTargetSameInstantApp =
8200                        comp.getPackageName().equals(instantAppPkgName);
8201                final boolean isTargetInstantApp =
8202                        (ai.applicationInfo.privateFlags
8203                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8204                final boolean isTargetVisibleToInstantApp =
8205                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8206                final boolean isTargetExplicitlyVisibleToInstantApp =
8207                        isTargetVisibleToInstantApp
8208                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8209                final boolean isTargetHiddenFromInstantApp =
8210                        !isTargetVisibleToInstantApp
8211                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8212                final boolean blockResolution =
8213                        !isTargetSameInstantApp
8214                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8215                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8216                                        && isTargetHiddenFromInstantApp));
8217                if (!blockResolution) {
8218                    ResolveInfo ri = new ResolveInfo();
8219                    ri.activityInfo = ai;
8220                    list.add(ri);
8221                }
8222            }
8223            return applyPostResolutionFilter(
8224                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8225        }
8226
8227        // reader
8228        synchronized (mPackages) {
8229            String pkgName = intent.getPackage();
8230            if (pkgName == null) {
8231                final List<ResolveInfo> result =
8232                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8233                return applyPostResolutionFilter(
8234                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8235            }
8236            final PackageParser.Package pkg = mPackages.get(pkgName);
8237            if (pkg != null) {
8238                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8239                        intent, resolvedType, flags, pkg.receivers, userId);
8240                return applyPostResolutionFilter(
8241                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8242            }
8243            return Collections.emptyList();
8244        }
8245    }
8246
8247    @Override
8248    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8249        final int callingUid = Binder.getCallingUid();
8250        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8251    }
8252
8253    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8254            int userId, int callingUid) {
8255        if (!sUserManager.exists(userId)) return null;
8256        flags = updateFlagsForResolve(
8257                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8258        List<ResolveInfo> query = queryIntentServicesInternal(
8259                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8260        if (query != null) {
8261            if (query.size() >= 1) {
8262                // If there is more than one service with the same priority,
8263                // just arbitrarily pick the first one.
8264                return query.get(0);
8265            }
8266        }
8267        return null;
8268    }
8269
8270    @Override
8271    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8272            String resolvedType, int flags, int userId) {
8273        final int callingUid = Binder.getCallingUid();
8274        return new ParceledListSlice<>(queryIntentServicesInternal(
8275                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8276    }
8277
8278    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8279            String resolvedType, int flags, int userId, int callingUid,
8280            boolean includeInstantApps) {
8281        if (!sUserManager.exists(userId)) return Collections.emptyList();
8282        enforceCrossUserPermission(callingUid, userId,
8283                false /*requireFullPermission*/, false /*checkShell*/,
8284                "query intent receivers");
8285        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8286        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8287        ComponentName comp = intent.getComponent();
8288        if (comp == null) {
8289            if (intent.getSelector() != null) {
8290                intent = intent.getSelector();
8291                comp = intent.getComponent();
8292            }
8293        }
8294        if (comp != null) {
8295            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8296            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8297            if (si != null) {
8298                // When specifying an explicit component, we prevent the service from being
8299                // used when either 1) the service is in an instant application and the
8300                // caller is not the same instant application or 2) the calling package is
8301                // ephemeral and the activity is not visible to ephemeral applications.
8302                final boolean matchInstantApp =
8303                        (flags & PackageManager.MATCH_INSTANT) != 0;
8304                final boolean matchVisibleToInstantAppOnly =
8305                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8306                final boolean isCallerInstantApp =
8307                        instantAppPkgName != null;
8308                final boolean isTargetSameInstantApp =
8309                        comp.getPackageName().equals(instantAppPkgName);
8310                final boolean isTargetInstantApp =
8311                        (si.applicationInfo.privateFlags
8312                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8313                final boolean isTargetHiddenFromInstantApp =
8314                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8315                final boolean blockResolution =
8316                        !isTargetSameInstantApp
8317                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8318                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8319                                        && isTargetHiddenFromInstantApp));
8320                if (!blockResolution) {
8321                    final ResolveInfo ri = new ResolveInfo();
8322                    ri.serviceInfo = si;
8323                    list.add(ri);
8324                }
8325            }
8326            return list;
8327        }
8328
8329        // reader
8330        synchronized (mPackages) {
8331            String pkgName = intent.getPackage();
8332            if (pkgName == null) {
8333                return applyPostServiceResolutionFilter(
8334                        mServices.queryIntent(intent, resolvedType, flags, userId),
8335                        instantAppPkgName);
8336            }
8337            final PackageParser.Package pkg = mPackages.get(pkgName);
8338            if (pkg != null) {
8339                return applyPostServiceResolutionFilter(
8340                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8341                                userId),
8342                        instantAppPkgName);
8343            }
8344            return Collections.emptyList();
8345        }
8346    }
8347
8348    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8349            String instantAppPkgName) {
8350        if (instantAppPkgName == null) {
8351            return resolveInfos;
8352        }
8353        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8354            final ResolveInfo info = resolveInfos.get(i);
8355            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8356            // allow services that are defined in the provided package
8357            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8358                if (info.serviceInfo.splitName != null
8359                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8360                                info.serviceInfo.splitName)) {
8361                    // requested service is defined in a split that hasn't been installed yet.
8362                    // add the installer to the resolve list
8363                    if (DEBUG_EPHEMERAL) {
8364                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8365                    }
8366                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8367                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8368                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8369                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8370                            null /*failureIntent*/);
8371                    // make sure this resolver is the default
8372                    installerInfo.isDefault = true;
8373                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8374                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8375                    // add a non-generic filter
8376                    installerInfo.filter = new IntentFilter();
8377                    // load resources from the correct package
8378                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8379                    resolveInfos.set(i, installerInfo);
8380                }
8381                continue;
8382            }
8383            // allow services that have been explicitly exposed to ephemeral apps
8384            if (!isEphemeralApp
8385                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8386                continue;
8387            }
8388            resolveInfos.remove(i);
8389        }
8390        return resolveInfos;
8391    }
8392
8393    @Override
8394    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8395            String resolvedType, int flags, int userId) {
8396        return new ParceledListSlice<>(
8397                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8398    }
8399
8400    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8401            Intent intent, String resolvedType, int flags, int userId) {
8402        if (!sUserManager.exists(userId)) return Collections.emptyList();
8403        final int callingUid = Binder.getCallingUid();
8404        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8405        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8406                false /*includeInstantApps*/);
8407        ComponentName comp = intent.getComponent();
8408        if (comp == null) {
8409            if (intent.getSelector() != null) {
8410                intent = intent.getSelector();
8411                comp = intent.getComponent();
8412            }
8413        }
8414        if (comp != null) {
8415            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8416            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8417            if (pi != null) {
8418                // When specifying an explicit component, we prevent the provider from being
8419                // used when either 1) the provider is in an instant application and the
8420                // caller is not the same instant application or 2) the calling package is an
8421                // instant application and the provider is not visible to instant applications.
8422                final boolean matchInstantApp =
8423                        (flags & PackageManager.MATCH_INSTANT) != 0;
8424                final boolean matchVisibleToInstantAppOnly =
8425                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8426                final boolean isCallerInstantApp =
8427                        instantAppPkgName != null;
8428                final boolean isTargetSameInstantApp =
8429                        comp.getPackageName().equals(instantAppPkgName);
8430                final boolean isTargetInstantApp =
8431                        (pi.applicationInfo.privateFlags
8432                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8433                final boolean isTargetHiddenFromInstantApp =
8434                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8435                final boolean blockResolution =
8436                        !isTargetSameInstantApp
8437                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8438                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8439                                        && isTargetHiddenFromInstantApp));
8440                if (!blockResolution) {
8441                    final ResolveInfo ri = new ResolveInfo();
8442                    ri.providerInfo = pi;
8443                    list.add(ri);
8444                }
8445            }
8446            return list;
8447        }
8448
8449        // reader
8450        synchronized (mPackages) {
8451            String pkgName = intent.getPackage();
8452            if (pkgName == null) {
8453                return applyPostContentProviderResolutionFilter(
8454                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8455                        instantAppPkgName);
8456            }
8457            final PackageParser.Package pkg = mPackages.get(pkgName);
8458            if (pkg != null) {
8459                return applyPostContentProviderResolutionFilter(
8460                        mProviders.queryIntentForPackage(
8461                        intent, resolvedType, flags, pkg.providers, userId),
8462                        instantAppPkgName);
8463            }
8464            return Collections.emptyList();
8465        }
8466    }
8467
8468    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8469            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8470        if (instantAppPkgName == null) {
8471            return resolveInfos;
8472        }
8473        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8474            final ResolveInfo info = resolveInfos.get(i);
8475            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8476            // allow providers that are defined in the provided package
8477            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8478                if (info.providerInfo.splitName != null
8479                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8480                                info.providerInfo.splitName)) {
8481                    // requested provider is defined in a split that hasn't been installed yet.
8482                    // add the installer to the resolve list
8483                    if (DEBUG_EPHEMERAL) {
8484                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8485                    }
8486                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8487                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8488                            info.providerInfo.packageName, info.providerInfo.splitName,
8489                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8490                            null /*failureIntent*/);
8491                    // make sure this resolver is the default
8492                    installerInfo.isDefault = true;
8493                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8494                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8495                    // add a non-generic filter
8496                    installerInfo.filter = new IntentFilter();
8497                    // load resources from the correct package
8498                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8499                    resolveInfos.set(i, installerInfo);
8500                }
8501                continue;
8502            }
8503            // allow providers that have been explicitly exposed to instant applications
8504            if (!isEphemeralApp
8505                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8506                continue;
8507            }
8508            resolveInfos.remove(i);
8509        }
8510        return resolveInfos;
8511    }
8512
8513    @Override
8514    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8515        final int callingUid = Binder.getCallingUid();
8516        if (getInstantAppPackageName(callingUid) != null) {
8517            return ParceledListSlice.emptyList();
8518        }
8519        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8520        flags = updateFlagsForPackage(flags, userId, null);
8521        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8522        enforceCrossUserPermission(callingUid, userId,
8523                true /* requireFullPermission */, false /* checkShell */,
8524                "get installed packages");
8525
8526        // writer
8527        synchronized (mPackages) {
8528            ArrayList<PackageInfo> list;
8529            if (listUninstalled) {
8530                list = new ArrayList<>(mSettings.mPackages.size());
8531                for (PackageSetting ps : mSettings.mPackages.values()) {
8532                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8533                        continue;
8534                    }
8535                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8536                        continue;
8537                    }
8538                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8539                    if (pi != null) {
8540                        list.add(pi);
8541                    }
8542                }
8543            } else {
8544                list = new ArrayList<>(mPackages.size());
8545                for (PackageParser.Package p : mPackages.values()) {
8546                    final PackageSetting ps = (PackageSetting) p.mExtras;
8547                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8548                        continue;
8549                    }
8550                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8551                        continue;
8552                    }
8553                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8554                            p.mExtras, flags, userId);
8555                    if (pi != null) {
8556                        list.add(pi);
8557                    }
8558                }
8559            }
8560
8561            return new ParceledListSlice<>(list);
8562        }
8563    }
8564
8565    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8566            String[] permissions, boolean[] tmp, int flags, int userId) {
8567        int numMatch = 0;
8568        final PermissionsState permissionsState = ps.getPermissionsState();
8569        for (int i=0; i<permissions.length; i++) {
8570            final String permission = permissions[i];
8571            if (permissionsState.hasPermission(permission, userId)) {
8572                tmp[i] = true;
8573                numMatch++;
8574            } else {
8575                tmp[i] = false;
8576            }
8577        }
8578        if (numMatch == 0) {
8579            return;
8580        }
8581        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8582
8583        // The above might return null in cases of uninstalled apps or install-state
8584        // skew across users/profiles.
8585        if (pi != null) {
8586            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8587                if (numMatch == permissions.length) {
8588                    pi.requestedPermissions = permissions;
8589                } else {
8590                    pi.requestedPermissions = new String[numMatch];
8591                    numMatch = 0;
8592                    for (int i=0; i<permissions.length; i++) {
8593                        if (tmp[i]) {
8594                            pi.requestedPermissions[numMatch] = permissions[i];
8595                            numMatch++;
8596                        }
8597                    }
8598                }
8599            }
8600            list.add(pi);
8601        }
8602    }
8603
8604    @Override
8605    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8606            String[] permissions, int flags, int userId) {
8607        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8608        flags = updateFlagsForPackage(flags, userId, permissions);
8609        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8610                true /* requireFullPermission */, false /* checkShell */,
8611                "get packages holding permissions");
8612        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8613
8614        // writer
8615        synchronized (mPackages) {
8616            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8617            boolean[] tmpBools = new boolean[permissions.length];
8618            if (listUninstalled) {
8619                for (PackageSetting ps : mSettings.mPackages.values()) {
8620                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8621                            userId);
8622                }
8623            } else {
8624                for (PackageParser.Package pkg : mPackages.values()) {
8625                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8626                    if (ps != null) {
8627                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8628                                userId);
8629                    }
8630                }
8631            }
8632
8633            return new ParceledListSlice<PackageInfo>(list);
8634        }
8635    }
8636
8637    @Override
8638    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8639        final int callingUid = Binder.getCallingUid();
8640        if (getInstantAppPackageName(callingUid) != null) {
8641            return ParceledListSlice.emptyList();
8642        }
8643        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8644        flags = updateFlagsForApplication(flags, userId, null);
8645        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8646
8647        // writer
8648        synchronized (mPackages) {
8649            ArrayList<ApplicationInfo> list;
8650            if (listUninstalled) {
8651                list = new ArrayList<>(mSettings.mPackages.size());
8652                for (PackageSetting ps : mSettings.mPackages.values()) {
8653                    ApplicationInfo ai;
8654                    int effectiveFlags = flags;
8655                    if (ps.isSystem()) {
8656                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8657                    }
8658                    if (ps.pkg != null) {
8659                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8660                            continue;
8661                        }
8662                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8663                            continue;
8664                        }
8665                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8666                                ps.readUserState(userId), userId);
8667                        if (ai != null) {
8668                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8669                        }
8670                    } else {
8671                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8672                        // and already converts to externally visible package name
8673                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8674                                callingUid, effectiveFlags, userId);
8675                    }
8676                    if (ai != null) {
8677                        list.add(ai);
8678                    }
8679                }
8680            } else {
8681                list = new ArrayList<>(mPackages.size());
8682                for (PackageParser.Package p : mPackages.values()) {
8683                    if (p.mExtras != null) {
8684                        PackageSetting ps = (PackageSetting) p.mExtras;
8685                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8686                            continue;
8687                        }
8688                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8689                            continue;
8690                        }
8691                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8692                                ps.readUserState(userId), userId);
8693                        if (ai != null) {
8694                            ai.packageName = resolveExternalPackageNameLPr(p);
8695                            list.add(ai);
8696                        }
8697                    }
8698                }
8699            }
8700
8701            return new ParceledListSlice<>(list);
8702        }
8703    }
8704
8705    @Override
8706    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8707        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8708            return null;
8709        }
8710        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8711            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8712                    "getEphemeralApplications");
8713        }
8714        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8715                true /* requireFullPermission */, false /* checkShell */,
8716                "getEphemeralApplications");
8717        synchronized (mPackages) {
8718            List<InstantAppInfo> instantApps = mInstantAppRegistry
8719                    .getInstantAppsLPr(userId);
8720            if (instantApps != null) {
8721                return new ParceledListSlice<>(instantApps);
8722            }
8723        }
8724        return null;
8725    }
8726
8727    @Override
8728    public boolean isInstantApp(String packageName, int userId) {
8729        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8730                true /* requireFullPermission */, false /* checkShell */,
8731                "isInstantApp");
8732        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8733            return false;
8734        }
8735
8736        synchronized (mPackages) {
8737            int callingUid = Binder.getCallingUid();
8738            if (Process.isIsolated(callingUid)) {
8739                callingUid = mIsolatedOwners.get(callingUid);
8740            }
8741            final PackageSetting ps = mSettings.mPackages.get(packageName);
8742            PackageParser.Package pkg = mPackages.get(packageName);
8743            final boolean returnAllowed =
8744                    ps != null
8745                    && (isCallerSameApp(packageName, callingUid)
8746                            || canViewInstantApps(callingUid, userId)
8747                            || mInstantAppRegistry.isInstantAccessGranted(
8748                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8749            if (returnAllowed) {
8750                return ps.getInstantApp(userId);
8751            }
8752        }
8753        return false;
8754    }
8755
8756    @Override
8757    public byte[] getInstantAppCookie(String packageName, int userId) {
8758        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8759            return null;
8760        }
8761
8762        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8763                true /* requireFullPermission */, false /* checkShell */,
8764                "getInstantAppCookie");
8765        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8766            return null;
8767        }
8768        synchronized (mPackages) {
8769            return mInstantAppRegistry.getInstantAppCookieLPw(
8770                    packageName, userId);
8771        }
8772    }
8773
8774    @Override
8775    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8776        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8777            return true;
8778        }
8779
8780        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8781                true /* requireFullPermission */, true /* checkShell */,
8782                "setInstantAppCookie");
8783        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8784            return false;
8785        }
8786        synchronized (mPackages) {
8787            return mInstantAppRegistry.setInstantAppCookieLPw(
8788                    packageName, cookie, userId);
8789        }
8790    }
8791
8792    @Override
8793    public Bitmap getInstantAppIcon(String packageName, int userId) {
8794        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8795            return null;
8796        }
8797
8798        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8799            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8800                    "getInstantAppIcon");
8801        }
8802        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8803                true /* requireFullPermission */, false /* checkShell */,
8804                "getInstantAppIcon");
8805
8806        synchronized (mPackages) {
8807            return mInstantAppRegistry.getInstantAppIconLPw(
8808                    packageName, userId);
8809        }
8810    }
8811
8812    private boolean isCallerSameApp(String packageName, int uid) {
8813        PackageParser.Package pkg = mPackages.get(packageName);
8814        return pkg != null
8815                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8816    }
8817
8818    @Override
8819    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8820        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8821            return ParceledListSlice.emptyList();
8822        }
8823        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8824    }
8825
8826    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8827        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8828
8829        // reader
8830        synchronized (mPackages) {
8831            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8832            final int userId = UserHandle.getCallingUserId();
8833            while (i.hasNext()) {
8834                final PackageParser.Package p = i.next();
8835                if (p.applicationInfo == null) continue;
8836
8837                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8838                        && !p.applicationInfo.isDirectBootAware();
8839                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8840                        && p.applicationInfo.isDirectBootAware();
8841
8842                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8843                        && (!mSafeMode || isSystemApp(p))
8844                        && (matchesUnaware || matchesAware)) {
8845                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8846                    if (ps != null) {
8847                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8848                                ps.readUserState(userId), userId);
8849                        if (ai != null) {
8850                            finalList.add(ai);
8851                        }
8852                    }
8853                }
8854            }
8855        }
8856
8857        return finalList;
8858    }
8859
8860    @Override
8861    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8862        if (!sUserManager.exists(userId)) return null;
8863        flags = updateFlagsForComponent(flags, userId, name);
8864        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8865        // reader
8866        synchronized (mPackages) {
8867            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8868            PackageSetting ps = provider != null
8869                    ? mSettings.mPackages.get(provider.owner.packageName)
8870                    : null;
8871            if (ps != null) {
8872                final boolean isInstantApp = ps.getInstantApp(userId);
8873                // normal application; filter out instant application provider
8874                if (instantAppPkgName == null && isInstantApp) {
8875                    return null;
8876                }
8877                // instant application; filter out other instant applications
8878                if (instantAppPkgName != null
8879                        && isInstantApp
8880                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8881                    return null;
8882                }
8883                // instant application; filter out non-exposed provider
8884                if (instantAppPkgName != null
8885                        && !isInstantApp
8886                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8887                    return null;
8888                }
8889                // provider not enabled
8890                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8891                    return null;
8892                }
8893                return PackageParser.generateProviderInfo(
8894                        provider, flags, ps.readUserState(userId), userId);
8895            }
8896            return null;
8897        }
8898    }
8899
8900    /**
8901     * @deprecated
8902     */
8903    @Deprecated
8904    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8905        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8906            return;
8907        }
8908        // reader
8909        synchronized (mPackages) {
8910            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8911                    .entrySet().iterator();
8912            final int userId = UserHandle.getCallingUserId();
8913            while (i.hasNext()) {
8914                Map.Entry<String, PackageParser.Provider> entry = i.next();
8915                PackageParser.Provider p = entry.getValue();
8916                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8917
8918                if (ps != null && p.syncable
8919                        && (!mSafeMode || (p.info.applicationInfo.flags
8920                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8921                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8922                            ps.readUserState(userId), userId);
8923                    if (info != null) {
8924                        outNames.add(entry.getKey());
8925                        outInfo.add(info);
8926                    }
8927                }
8928            }
8929        }
8930    }
8931
8932    @Override
8933    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8934            int uid, int flags, String metaDataKey) {
8935        final int callingUid = Binder.getCallingUid();
8936        final int userId = processName != null ? UserHandle.getUserId(uid)
8937                : UserHandle.getCallingUserId();
8938        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8939        flags = updateFlagsForComponent(flags, userId, processName);
8940        ArrayList<ProviderInfo> finalList = null;
8941        // reader
8942        synchronized (mPackages) {
8943            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8944            while (i.hasNext()) {
8945                final PackageParser.Provider p = i.next();
8946                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8947                if (ps != null && p.info.authority != null
8948                        && (processName == null
8949                                || (p.info.processName.equals(processName)
8950                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8951                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8952
8953                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8954                    // parameter.
8955                    if (metaDataKey != null
8956                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8957                        continue;
8958                    }
8959                    final ComponentName component =
8960                            new ComponentName(p.info.packageName, p.info.name);
8961                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8962                        continue;
8963                    }
8964                    if (finalList == null) {
8965                        finalList = new ArrayList<ProviderInfo>(3);
8966                    }
8967                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8968                            ps.readUserState(userId), userId);
8969                    if (info != null) {
8970                        finalList.add(info);
8971                    }
8972                }
8973            }
8974        }
8975
8976        if (finalList != null) {
8977            Collections.sort(finalList, mProviderInitOrderSorter);
8978            return new ParceledListSlice<ProviderInfo>(finalList);
8979        }
8980
8981        return ParceledListSlice.emptyList();
8982    }
8983
8984    @Override
8985    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8986        // reader
8987        synchronized (mPackages) {
8988            final int callingUid = Binder.getCallingUid();
8989            final int callingUserId = UserHandle.getUserId(callingUid);
8990            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8991            if (ps == null) return null;
8992            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8993                return null;
8994            }
8995            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8996            return PackageParser.generateInstrumentationInfo(i, flags);
8997        }
8998    }
8999
9000    @Override
9001    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
9002            String targetPackage, int flags) {
9003        final int callingUid = Binder.getCallingUid();
9004        final int callingUserId = UserHandle.getUserId(callingUid);
9005        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
9006        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
9007            return ParceledListSlice.emptyList();
9008        }
9009        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
9010    }
9011
9012    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
9013            int flags) {
9014        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
9015
9016        // reader
9017        synchronized (mPackages) {
9018            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
9019            while (i.hasNext()) {
9020                final PackageParser.Instrumentation p = i.next();
9021                if (targetPackage == null
9022                        || targetPackage.equals(p.info.targetPackage)) {
9023                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
9024                            flags);
9025                    if (ii != null) {
9026                        finalList.add(ii);
9027                    }
9028                }
9029            }
9030        }
9031
9032        return finalList;
9033    }
9034
9035    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9036        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9037        try {
9038            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9039        } finally {
9040            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9041        }
9042    }
9043
9044    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9045        final File[] files = dir.listFiles();
9046        if (ArrayUtils.isEmpty(files)) {
9047            Log.d(TAG, "No files in app dir " + dir);
9048            return;
9049        }
9050
9051        if (DEBUG_PACKAGE_SCANNING) {
9052            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9053                    + " flags=0x" + Integer.toHexString(parseFlags));
9054        }
9055        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9056                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9057                mParallelPackageParserCallback);
9058
9059        // Submit files for parsing in parallel
9060        int fileCount = 0;
9061        for (File file : files) {
9062            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9063                    && !PackageInstallerService.isStageName(file.getName());
9064            if (!isPackage) {
9065                // Ignore entries which are not packages
9066                continue;
9067            }
9068            parallelPackageParser.submit(file, parseFlags);
9069            fileCount++;
9070        }
9071
9072        // Process results one by one
9073        for (; fileCount > 0; fileCount--) {
9074            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9075            Throwable throwable = parseResult.throwable;
9076            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9077
9078            if (throwable == null) {
9079                // Static shared libraries have synthetic package names
9080                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9081                    renameStaticSharedLibraryPackage(parseResult.pkg);
9082                }
9083                try {
9084                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9085                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9086                                currentTime, null);
9087                    }
9088                } catch (PackageManagerException e) {
9089                    errorCode = e.error;
9090                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9091                }
9092            } else if (throwable instanceof PackageParser.PackageParserException) {
9093                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9094                        throwable;
9095                errorCode = e.error;
9096                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9097            } else {
9098                throw new IllegalStateException("Unexpected exception occurred while parsing "
9099                        + parseResult.scanFile, throwable);
9100            }
9101
9102            // Delete invalid userdata apps
9103            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9104                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9105                logCriticalInfo(Log.WARN,
9106                        "Deleting invalid package at " + parseResult.scanFile);
9107                removeCodePathLI(parseResult.scanFile);
9108            }
9109        }
9110        parallelPackageParser.close();
9111    }
9112
9113    private static File getSettingsProblemFile() {
9114        File dataDir = Environment.getDataDirectory();
9115        File systemDir = new File(dataDir, "system");
9116        File fname = new File(systemDir, "uiderrors.txt");
9117        return fname;
9118    }
9119
9120    static void reportSettingsProblem(int priority, String msg) {
9121        logCriticalInfo(priority, msg);
9122    }
9123
9124    public static void logCriticalInfo(int priority, String msg) {
9125        Slog.println(priority, TAG, msg);
9126        EventLogTags.writePmCriticalInfo(msg);
9127        try {
9128            File fname = getSettingsProblemFile();
9129            FileOutputStream out = new FileOutputStream(fname, true);
9130            PrintWriter pw = new FastPrintWriter(out);
9131            SimpleDateFormat formatter = new SimpleDateFormat();
9132            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9133            pw.println(dateString + ": " + msg);
9134            pw.close();
9135            FileUtils.setPermissions(
9136                    fname.toString(),
9137                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9138                    -1, -1);
9139        } catch (java.io.IOException e) {
9140        }
9141    }
9142
9143    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9144        if (srcFile.isDirectory()) {
9145            final File baseFile = new File(pkg.baseCodePath);
9146            long maxModifiedTime = baseFile.lastModified();
9147            if (pkg.splitCodePaths != null) {
9148                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9149                    final File splitFile = new File(pkg.splitCodePaths[i]);
9150                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9151                }
9152            }
9153            return maxModifiedTime;
9154        }
9155        return srcFile.lastModified();
9156    }
9157
9158    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9159            final int policyFlags) throws PackageManagerException {
9160        // When upgrading from pre-N MR1, verify the package time stamp using the package
9161        // directory and not the APK file.
9162        final long lastModifiedTime = mIsPreNMR1Upgrade
9163                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9164        if (ps != null
9165                && ps.codePath.equals(srcFile)
9166                && ps.timeStamp == lastModifiedTime
9167                && !isCompatSignatureUpdateNeeded(pkg)
9168                && !isRecoverSignatureUpdateNeeded(pkg)) {
9169            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9170            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9171            ArraySet<PublicKey> signingKs;
9172            synchronized (mPackages) {
9173                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9174            }
9175            if (ps.signatures.mSignatures != null
9176                    && ps.signatures.mSignatures.length != 0
9177                    && signingKs != null) {
9178                // Optimization: reuse the existing cached certificates
9179                // if the package appears to be unchanged.
9180                pkg.mSignatures = ps.signatures.mSignatures;
9181                pkg.mSigningKeys = signingKs;
9182                return;
9183            }
9184
9185            Slog.w(TAG, "PackageSetting for " + ps.name
9186                    + " is missing signatures.  Collecting certs again to recover them.");
9187        } else {
9188            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9189        }
9190
9191        try {
9192            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9193            PackageParser.collectCertificates(pkg, policyFlags);
9194        } catch (PackageParserException e) {
9195            throw PackageManagerException.from(e);
9196        } finally {
9197            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9198        }
9199    }
9200
9201    /**
9202     *  Traces a package scan.
9203     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9204     */
9205    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9206            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9207        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9208        try {
9209            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9210        } finally {
9211            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9212        }
9213    }
9214
9215    /**
9216     *  Scans a package and returns the newly parsed package.
9217     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9218     */
9219    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9220            long currentTime, UserHandle user) throws PackageManagerException {
9221        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9222        PackageParser pp = new PackageParser();
9223        pp.setSeparateProcesses(mSeparateProcesses);
9224        pp.setOnlyCoreApps(mOnlyCore);
9225        pp.setDisplayMetrics(mMetrics);
9226        pp.setCallback(mPackageParserCallback);
9227
9228        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9229            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9230        }
9231
9232        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9233        final PackageParser.Package pkg;
9234        try {
9235            pkg = pp.parsePackage(scanFile, parseFlags);
9236        } catch (PackageParserException e) {
9237            throw PackageManagerException.from(e);
9238        } finally {
9239            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9240        }
9241
9242        // Static shared libraries have synthetic package names
9243        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9244            renameStaticSharedLibraryPackage(pkg);
9245        }
9246
9247        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9248    }
9249
9250    /**
9251     *  Scans a package and returns the newly parsed package.
9252     *  @throws PackageManagerException on a parse error.
9253     */
9254    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9255            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9256            throws PackageManagerException {
9257        // If the package has children and this is the first dive in the function
9258        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9259        // packages (parent and children) would be successfully scanned before the
9260        // actual scan since scanning mutates internal state and we want to atomically
9261        // install the package and its children.
9262        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9263            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9264                scanFlags |= SCAN_CHECK_ONLY;
9265            }
9266        } else {
9267            scanFlags &= ~SCAN_CHECK_ONLY;
9268        }
9269
9270        // Scan the parent
9271        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9272                scanFlags, currentTime, user);
9273
9274        // Scan the children
9275        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9276        for (int i = 0; i < childCount; i++) {
9277            PackageParser.Package childPackage = pkg.childPackages.get(i);
9278            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9279                    currentTime, user);
9280        }
9281
9282
9283        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9284            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9285        }
9286
9287        return scannedPkg;
9288    }
9289
9290    /**
9291     *  Scans a package and returns the newly parsed package.
9292     *  @throws PackageManagerException on a parse error.
9293     */
9294    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9295            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9296            throws PackageManagerException {
9297        PackageSetting ps = null;
9298        PackageSetting updatedPkg;
9299        // reader
9300        synchronized (mPackages) {
9301            // Look to see if we already know about this package.
9302            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9303            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9304                // This package has been renamed to its original name.  Let's
9305                // use that.
9306                ps = mSettings.getPackageLPr(oldName);
9307            }
9308            // If there was no original package, see one for the real package name.
9309            if (ps == null) {
9310                ps = mSettings.getPackageLPr(pkg.packageName);
9311            }
9312            // Check to see if this package could be hiding/updating a system
9313            // package.  Must look for it either under the original or real
9314            // package name depending on our state.
9315            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9316            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9317
9318            // If this is a package we don't know about on the system partition, we
9319            // may need to remove disabled child packages on the system partition
9320            // or may need to not add child packages if the parent apk is updated
9321            // on the data partition and no longer defines this child package.
9322            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9323                // If this is a parent package for an updated system app and this system
9324                // app got an OTA update which no longer defines some of the child packages
9325                // we have to prune them from the disabled system packages.
9326                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9327                if (disabledPs != null) {
9328                    final int scannedChildCount = (pkg.childPackages != null)
9329                            ? pkg.childPackages.size() : 0;
9330                    final int disabledChildCount = disabledPs.childPackageNames != null
9331                            ? disabledPs.childPackageNames.size() : 0;
9332                    for (int i = 0; i < disabledChildCount; i++) {
9333                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9334                        boolean disabledPackageAvailable = false;
9335                        for (int j = 0; j < scannedChildCount; j++) {
9336                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9337                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9338                                disabledPackageAvailable = true;
9339                                break;
9340                            }
9341                         }
9342                         if (!disabledPackageAvailable) {
9343                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9344                         }
9345                    }
9346                }
9347            }
9348        }
9349
9350        final boolean isUpdatedPkg = updatedPkg != null;
9351        final boolean isUpdatedSystemPkg = isUpdatedPkg
9352                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9353        boolean isUpdatedPkgBetter = false;
9354        // First check if this is a system package that may involve an update
9355        if (isUpdatedSystemPkg) {
9356            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9357            // it needs to drop FLAG_PRIVILEGED.
9358            if (locationIsPrivileged(scanFile)) {
9359                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9360            } else {
9361                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9362            }
9363
9364            if (ps != null && !ps.codePath.equals(scanFile)) {
9365                // The path has changed from what was last scanned...  check the
9366                // version of the new path against what we have stored to determine
9367                // what to do.
9368                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9369                if (pkg.mVersionCode <= ps.versionCode) {
9370                    // The system package has been updated and the code path does not match
9371                    // Ignore entry. Skip it.
9372                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9373                            + " ignored: updated version " + ps.versionCode
9374                            + " better than this " + pkg.mVersionCode);
9375                    if (!updatedPkg.codePath.equals(scanFile)) {
9376                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9377                                + ps.name + " changing from " + updatedPkg.codePathString
9378                                + " to " + scanFile);
9379                        updatedPkg.codePath = scanFile;
9380                        updatedPkg.codePathString = scanFile.toString();
9381                        updatedPkg.resourcePath = scanFile;
9382                        updatedPkg.resourcePathString = scanFile.toString();
9383                    }
9384                    updatedPkg.pkg = pkg;
9385                    updatedPkg.versionCode = pkg.mVersionCode;
9386
9387                    // Update the disabled system child packages to point to the package too.
9388                    final int childCount = updatedPkg.childPackageNames != null
9389                            ? updatedPkg.childPackageNames.size() : 0;
9390                    for (int i = 0; i < childCount; i++) {
9391                        String childPackageName = updatedPkg.childPackageNames.get(i);
9392                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9393                                childPackageName);
9394                        if (updatedChildPkg != null) {
9395                            updatedChildPkg.pkg = pkg;
9396                            updatedChildPkg.versionCode = pkg.mVersionCode;
9397                        }
9398                    }
9399                } else {
9400                    // The current app on the system partition is better than
9401                    // what we have updated to on the data partition; switch
9402                    // back to the system partition version.
9403                    // At this point, its safely assumed that package installation for
9404                    // apps in system partition will go through. If not there won't be a working
9405                    // version of the app
9406                    // writer
9407                    synchronized (mPackages) {
9408                        // Just remove the loaded entries from package lists.
9409                        mPackages.remove(ps.name);
9410                    }
9411
9412                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9413                            + " reverting from " + ps.codePathString
9414                            + ": new version " + pkg.mVersionCode
9415                            + " better than installed " + ps.versionCode);
9416
9417                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9418                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9419                    synchronized (mInstallLock) {
9420                        args.cleanUpResourcesLI();
9421                    }
9422                    synchronized (mPackages) {
9423                        mSettings.enableSystemPackageLPw(ps.name);
9424                    }
9425                    isUpdatedPkgBetter = true;
9426                }
9427            }
9428        }
9429
9430        String resourcePath = null;
9431        String baseResourcePath = null;
9432        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9433            if (ps != null && ps.resourcePathString != null) {
9434                resourcePath = ps.resourcePathString;
9435                baseResourcePath = ps.resourcePathString;
9436            } else {
9437                // Should not happen at all. Just log an error.
9438                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9439            }
9440        } else {
9441            resourcePath = pkg.codePath;
9442            baseResourcePath = pkg.baseCodePath;
9443        }
9444
9445        // Set application objects path explicitly.
9446        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9447        pkg.setApplicationInfoCodePath(pkg.codePath);
9448        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9449        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9450        pkg.setApplicationInfoResourcePath(resourcePath);
9451        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9452        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9453
9454        // throw an exception if we have an update to a system application, but, it's not more
9455        // recent than the package we've already scanned
9456        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9457            // Set CPU Abis to application info.
9458            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9459                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9460                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9461            } else {
9462                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9463                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9464            }
9465
9466            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9467                    + scanFile + " ignored: updated version " + ps.versionCode
9468                    + " better than this " + pkg.mVersionCode);
9469        }
9470
9471        if (isUpdatedPkg) {
9472            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9473            // initially
9474            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9475
9476            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9477            // flag set initially
9478            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9479                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9480            }
9481        }
9482
9483        // Verify certificates against what was last scanned
9484        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9485
9486        /*
9487         * A new system app appeared, but we already had a non-system one of the
9488         * same name installed earlier.
9489         */
9490        boolean shouldHideSystemApp = false;
9491        if (!isUpdatedPkg && ps != null
9492                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9493            /*
9494             * Check to make sure the signatures match first. If they don't,
9495             * wipe the installed application and its data.
9496             */
9497            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9498                    != PackageManager.SIGNATURE_MATCH) {
9499                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9500                        + " signatures don't match existing userdata copy; removing");
9501                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9502                        "scanPackageInternalLI")) {
9503                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9504                }
9505                ps = null;
9506            } else {
9507                /*
9508                 * If the newly-added system app is an older version than the
9509                 * already installed version, hide it. It will be scanned later
9510                 * and re-added like an update.
9511                 */
9512                if (pkg.mVersionCode <= ps.versionCode) {
9513                    shouldHideSystemApp = true;
9514                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9515                            + " but new version " + pkg.mVersionCode + " better than installed "
9516                            + ps.versionCode + "; hiding system");
9517                } else {
9518                    /*
9519                     * The newly found system app is a newer version that the
9520                     * one previously installed. Simply remove the
9521                     * already-installed application and replace it with our own
9522                     * while keeping the application data.
9523                     */
9524                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9525                            + " reverting from " + ps.codePathString + ": new version "
9526                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9527                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9528                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9529                    synchronized (mInstallLock) {
9530                        args.cleanUpResourcesLI();
9531                    }
9532                }
9533            }
9534        }
9535
9536        // The apk is forward locked (not public) if its code and resources
9537        // are kept in different files. (except for app in either system or
9538        // vendor path).
9539        // TODO grab this value from PackageSettings
9540        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9541            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9542                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9543            }
9544        }
9545
9546        final int userId = ((user == null) ? 0 : user.getIdentifier());
9547        if (ps != null && ps.getInstantApp(userId)) {
9548            scanFlags |= SCAN_AS_INSTANT_APP;
9549        }
9550        if (ps != null && ps.getVirtulalPreload(userId)) {
9551            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9552        }
9553
9554        // Note that we invoke the following method only if we are about to unpack an application
9555        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9556                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9557
9558        /*
9559         * If the system app should be overridden by a previously installed
9560         * data, hide the system app now and let the /data/app scan pick it up
9561         * again.
9562         */
9563        if (shouldHideSystemApp) {
9564            synchronized (mPackages) {
9565                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9566            }
9567        }
9568
9569        return scannedPkg;
9570    }
9571
9572    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9573        // Derive the new package synthetic package name
9574        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9575                + pkg.staticSharedLibVersion);
9576    }
9577
9578    private static String fixProcessName(String defProcessName,
9579            String processName) {
9580        if (processName == null) {
9581            return defProcessName;
9582        }
9583        return processName;
9584    }
9585
9586    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9587            throws PackageManagerException {
9588        if (pkgSetting.signatures.mSignatures != null) {
9589            // Already existing package. Make sure signatures match
9590            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9591                    == PackageManager.SIGNATURE_MATCH;
9592            if (!match) {
9593                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9594                        == PackageManager.SIGNATURE_MATCH;
9595            }
9596            if (!match) {
9597                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9598                        == PackageManager.SIGNATURE_MATCH;
9599            }
9600            if (!match) {
9601                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9602                        + pkg.packageName + " signatures do not match the "
9603                        + "previously installed version; ignoring!");
9604            }
9605        }
9606
9607        // Check for shared user signatures
9608        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9609            // Already existing package. Make sure signatures match
9610            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9611                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9612            if (!match) {
9613                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9614                        == PackageManager.SIGNATURE_MATCH;
9615            }
9616            if (!match) {
9617                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9618                        == PackageManager.SIGNATURE_MATCH;
9619            }
9620            if (!match) {
9621                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9622                        "Package " + pkg.packageName
9623                        + " has no signatures that match those in shared user "
9624                        + pkgSetting.sharedUser.name + "; ignoring!");
9625            }
9626        }
9627    }
9628
9629    /**
9630     * Enforces that only the system UID or root's UID can call a method exposed
9631     * via Binder.
9632     *
9633     * @param message used as message if SecurityException is thrown
9634     * @throws SecurityException if the caller is not system or root
9635     */
9636    private static final void enforceSystemOrRoot(String message) {
9637        final int uid = Binder.getCallingUid();
9638        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9639            throw new SecurityException(message);
9640        }
9641    }
9642
9643    @Override
9644    public void performFstrimIfNeeded() {
9645        enforceSystemOrRoot("Only the system can request fstrim");
9646
9647        // Before everything else, see whether we need to fstrim.
9648        try {
9649            IStorageManager sm = PackageHelper.getStorageManager();
9650            if (sm != null) {
9651                boolean doTrim = false;
9652                final long interval = android.provider.Settings.Global.getLong(
9653                        mContext.getContentResolver(),
9654                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9655                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9656                if (interval > 0) {
9657                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9658                    if (timeSinceLast > interval) {
9659                        doTrim = true;
9660                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9661                                + "; running immediately");
9662                    }
9663                }
9664                if (doTrim) {
9665                    final boolean dexOptDialogShown;
9666                    synchronized (mPackages) {
9667                        dexOptDialogShown = mDexOptDialogShown;
9668                    }
9669                    if (!isFirstBoot() && dexOptDialogShown) {
9670                        try {
9671                            ActivityManager.getService().showBootMessage(
9672                                    mContext.getResources().getString(
9673                                            R.string.android_upgrading_fstrim), true);
9674                        } catch (RemoteException e) {
9675                        }
9676                    }
9677                    sm.runMaintenance();
9678                }
9679            } else {
9680                Slog.e(TAG, "storageManager service unavailable!");
9681            }
9682        } catch (RemoteException e) {
9683            // Can't happen; StorageManagerService is local
9684        }
9685    }
9686
9687    @Override
9688    public void updatePackagesIfNeeded() {
9689        enforceSystemOrRoot("Only the system can request package update");
9690
9691        // We need to re-extract after an OTA.
9692        boolean causeUpgrade = isUpgrade();
9693
9694        // First boot or factory reset.
9695        // Note: we also handle devices that are upgrading to N right now as if it is their
9696        //       first boot, as they do not have profile data.
9697        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9698
9699        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9700        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9701
9702        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9703            return;
9704        }
9705
9706        List<PackageParser.Package> pkgs;
9707        synchronized (mPackages) {
9708            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9709        }
9710
9711        final long startTime = System.nanoTime();
9712        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9713                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9714                    false /* bootComplete */);
9715
9716        final int elapsedTimeSeconds =
9717                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9718
9719        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9720        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9721        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9722        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9723        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9724    }
9725
9726    /*
9727     * Return the prebuilt profile path given a package base code path.
9728     */
9729    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9730        return pkg.baseCodePath + ".prof";
9731    }
9732
9733    /**
9734     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9735     * containing statistics about the invocation. The array consists of three elements,
9736     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9737     * and {@code numberOfPackagesFailed}.
9738     */
9739    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9740            final String compilerFilter, boolean bootComplete) {
9741
9742        int numberOfPackagesVisited = 0;
9743        int numberOfPackagesOptimized = 0;
9744        int numberOfPackagesSkipped = 0;
9745        int numberOfPackagesFailed = 0;
9746        final int numberOfPackagesToDexopt = pkgs.size();
9747
9748        for (PackageParser.Package pkg : pkgs) {
9749            numberOfPackagesVisited++;
9750
9751            boolean useProfileForDexopt = false;
9752
9753            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9754                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9755                // that are already compiled.
9756                File profileFile = new File(getPrebuildProfilePath(pkg));
9757                // Copy profile if it exists.
9758                if (profileFile.exists()) {
9759                    try {
9760                        // We could also do this lazily before calling dexopt in
9761                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9762                        // is that we don't have a good way to say "do this only once".
9763                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9764                                pkg.applicationInfo.uid, pkg.packageName,
9765                                ArtManager.getProfileName(null))) {
9766                            Log.e(TAG, "Installer failed to copy system profile!");
9767                        } else {
9768                            // Disabled as this causes speed-profile compilation during first boot
9769                            // even if things are already compiled.
9770                            // useProfileForDexopt = true;
9771                        }
9772                    } catch (Exception e) {
9773                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9774                                e);
9775                    }
9776                } else {
9777                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9778                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9779                    // minimize the number off apps being speed-profile compiled during first boot.
9780                    // The other paths will not change the filter.
9781                    if (disabledPs != null && disabledPs.pkg.isStub) {
9782                        // The package is the stub one, remove the stub suffix to get the normal
9783                        // package and APK names.
9784                        String systemProfilePath =
9785                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9786                        profileFile = new File(systemProfilePath);
9787                        // If we have a profile for a compressed APK, copy it to the reference
9788                        // location.
9789                        // Note that copying the profile here will cause it to override the
9790                        // reference profile every OTA even though the existing reference profile
9791                        // may have more data. We can't copy during decompression since the
9792                        // directories are not set up at that point.
9793                        if (profileFile.exists()) {
9794                            try {
9795                                // We could also do this lazily before calling dexopt in
9796                                // PackageDexOptimizer to prevent this happening on first boot. The
9797                                // issue is that we don't have a good way to say "do this only
9798                                // once".
9799                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9800                                        pkg.applicationInfo.uid, pkg.packageName,
9801                                        ArtManager.getProfileName(null))) {
9802                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9803                                } else {
9804                                    useProfileForDexopt = true;
9805                                }
9806                            } catch (Exception e) {
9807                                Log.e(TAG, "Failed to copy profile " +
9808                                        profileFile.getAbsolutePath() + " ", e);
9809                            }
9810                        }
9811                    }
9812                }
9813            }
9814
9815            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9816                if (DEBUG_DEXOPT) {
9817                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9818                }
9819                numberOfPackagesSkipped++;
9820                continue;
9821            }
9822
9823            if (DEBUG_DEXOPT) {
9824                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9825                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9826            }
9827
9828            if (showDialog) {
9829                try {
9830                    ActivityManager.getService().showBootMessage(
9831                            mContext.getResources().getString(R.string.android_upgrading_apk,
9832                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9833                } catch (RemoteException e) {
9834                }
9835                synchronized (mPackages) {
9836                    mDexOptDialogShown = true;
9837                }
9838            }
9839
9840            String pkgCompilerFilter = compilerFilter;
9841            if (useProfileForDexopt) {
9842                // Use background dexopt mode to try and use the profile. Note that this does not
9843                // guarantee usage of the profile.
9844                pkgCompilerFilter =
9845                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9846                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9847            }
9848
9849            // checkProfiles is false to avoid merging profiles during boot which
9850            // might interfere with background compilation (b/28612421).
9851            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9852            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9853            // trade-off worth doing to save boot time work.
9854            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9855            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9856                    pkg.packageName,
9857                    pkgCompilerFilter,
9858                    dexoptFlags));
9859
9860            switch (primaryDexOptStaus) {
9861                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9862                    numberOfPackagesOptimized++;
9863                    break;
9864                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9865                    numberOfPackagesSkipped++;
9866                    break;
9867                case PackageDexOptimizer.DEX_OPT_FAILED:
9868                    numberOfPackagesFailed++;
9869                    break;
9870                default:
9871                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9872                    break;
9873            }
9874        }
9875
9876        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9877                numberOfPackagesFailed };
9878    }
9879
9880    @Override
9881    public void notifyPackageUse(String packageName, int reason) {
9882        synchronized (mPackages) {
9883            final int callingUid = Binder.getCallingUid();
9884            final int callingUserId = UserHandle.getUserId(callingUid);
9885            if (getInstantAppPackageName(callingUid) != null) {
9886                if (!isCallerSameApp(packageName, callingUid)) {
9887                    return;
9888                }
9889            } else {
9890                if (isInstantApp(packageName, callingUserId)) {
9891                    return;
9892                }
9893            }
9894            notifyPackageUseLocked(packageName, reason);
9895        }
9896    }
9897
9898    private void notifyPackageUseLocked(String packageName, int reason) {
9899        final PackageParser.Package p = mPackages.get(packageName);
9900        if (p == null) {
9901            return;
9902        }
9903        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9904    }
9905
9906    @Override
9907    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9908            List<String> classPaths, String loaderIsa) {
9909        int userId = UserHandle.getCallingUserId();
9910        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9911        if (ai == null) {
9912            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9913                + loadingPackageName + ", user=" + userId);
9914            return;
9915        }
9916        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9917    }
9918
9919    @Override
9920    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9921            IDexModuleRegisterCallback callback) {
9922        int userId = UserHandle.getCallingUserId();
9923        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9924        DexManager.RegisterDexModuleResult result;
9925        if (ai == null) {
9926            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9927                     " calling user. package=" + packageName + ", user=" + userId);
9928            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9929        } else {
9930            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9931        }
9932
9933        if (callback != null) {
9934            mHandler.post(() -> {
9935                try {
9936                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9937                } catch (RemoteException e) {
9938                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9939                }
9940            });
9941        }
9942    }
9943
9944    /**
9945     * Ask the package manager to perform a dex-opt with the given compiler filter.
9946     *
9947     * Note: exposed only for the shell command to allow moving packages explicitly to a
9948     *       definite state.
9949     */
9950    @Override
9951    public boolean performDexOptMode(String packageName,
9952            boolean checkProfiles, String targetCompilerFilter, boolean force,
9953            boolean bootComplete, String splitName) {
9954        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9955                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9956                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9957        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9958                splitName, flags));
9959    }
9960
9961    /**
9962     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9963     * secondary dex files belonging to the given package.
9964     *
9965     * Note: exposed only for the shell command to allow moving packages explicitly to a
9966     *       definite state.
9967     */
9968    @Override
9969    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9970            boolean force) {
9971        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9972                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9973                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9974                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9975        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9976    }
9977
9978    /*package*/ boolean performDexOpt(DexoptOptions options) {
9979        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9980            return false;
9981        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9982            return false;
9983        }
9984
9985        if (options.isDexoptOnlySecondaryDex()) {
9986            return mDexManager.dexoptSecondaryDex(options);
9987        } else {
9988            int dexoptStatus = performDexOptWithStatus(options);
9989            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9990        }
9991    }
9992
9993    /**
9994     * Perform dexopt on the given package and return one of following result:
9995     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9996     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9997     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9998     */
9999    /* package */ int performDexOptWithStatus(DexoptOptions options) {
10000        return performDexOptTraced(options);
10001    }
10002
10003    private int performDexOptTraced(DexoptOptions options) {
10004        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10005        try {
10006            return performDexOptInternal(options);
10007        } finally {
10008            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10009        }
10010    }
10011
10012    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
10013    // if the package can now be considered up to date for the given filter.
10014    private int performDexOptInternal(DexoptOptions options) {
10015        PackageParser.Package p;
10016        synchronized (mPackages) {
10017            p = mPackages.get(options.getPackageName());
10018            if (p == null) {
10019                // Package could not be found. Report failure.
10020                return PackageDexOptimizer.DEX_OPT_FAILED;
10021            }
10022            mPackageUsage.maybeWriteAsync(mPackages);
10023            mCompilerStats.maybeWriteAsync();
10024        }
10025        long callingId = Binder.clearCallingIdentity();
10026        try {
10027            synchronized (mInstallLock) {
10028                return performDexOptInternalWithDependenciesLI(p, options);
10029            }
10030        } finally {
10031            Binder.restoreCallingIdentity(callingId);
10032        }
10033    }
10034
10035    public ArraySet<String> getOptimizablePackages() {
10036        ArraySet<String> pkgs = new ArraySet<String>();
10037        synchronized (mPackages) {
10038            for (PackageParser.Package p : mPackages.values()) {
10039                if (PackageDexOptimizer.canOptimizePackage(p)) {
10040                    pkgs.add(p.packageName);
10041                }
10042            }
10043        }
10044        return pkgs;
10045    }
10046
10047    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
10048            DexoptOptions options) {
10049        // Select the dex optimizer based on the force parameter.
10050        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
10051        //       allocate an object here.
10052        PackageDexOptimizer pdo = options.isForce()
10053                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
10054                : mPackageDexOptimizer;
10055
10056        // Dexopt all dependencies first. Note: we ignore the return value and march on
10057        // on errors.
10058        // Note that we are going to call performDexOpt on those libraries as many times as
10059        // they are referenced in packages. When we do a batch of performDexOpt (for example
10060        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
10061        // and the first package that uses the library will dexopt it. The
10062        // others will see that the compiled code for the library is up to date.
10063        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
10064        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10065        if (!deps.isEmpty()) {
10066            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10067                    options.getCompilerFilter(), options.getSplitName(),
10068                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10069            for (PackageParser.Package depPackage : deps) {
10070                // TODO: Analyze and investigate if we (should) profile libraries.
10071                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10072                        getOrCreateCompilerPackageStats(depPackage),
10073                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10074            }
10075        }
10076        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10077                getOrCreateCompilerPackageStats(p),
10078                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10079    }
10080
10081    /**
10082     * Reconcile the information we have about the secondary dex files belonging to
10083     * {@code packagName} and the actual dex files. For all dex files that were
10084     * deleted, update the internal records and delete the generated oat files.
10085     */
10086    @Override
10087    public void reconcileSecondaryDexFiles(String packageName) {
10088        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10089            return;
10090        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10091            return;
10092        }
10093        mDexManager.reconcileSecondaryDexFiles(packageName);
10094    }
10095
10096    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10097    // a reference there.
10098    /*package*/ DexManager getDexManager() {
10099        return mDexManager;
10100    }
10101
10102    /**
10103     * Execute the background dexopt job immediately.
10104     */
10105    @Override
10106    public boolean runBackgroundDexoptJob() {
10107        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10108            return false;
10109        }
10110        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10111    }
10112
10113    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10114        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10115                || p.usesStaticLibraries != null) {
10116            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10117            Set<String> collectedNames = new HashSet<>();
10118            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10119
10120            retValue.remove(p);
10121
10122            return retValue;
10123        } else {
10124            return Collections.emptyList();
10125        }
10126    }
10127
10128    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10129            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10130        if (!collectedNames.contains(p.packageName)) {
10131            collectedNames.add(p.packageName);
10132            collected.add(p);
10133
10134            if (p.usesLibraries != null) {
10135                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10136                        null, collected, collectedNames);
10137            }
10138            if (p.usesOptionalLibraries != null) {
10139                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10140                        null, collected, collectedNames);
10141            }
10142            if (p.usesStaticLibraries != null) {
10143                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10144                        p.usesStaticLibrariesVersions, collected, collectedNames);
10145            }
10146        }
10147    }
10148
10149    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10150            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10151        final int libNameCount = libs.size();
10152        for (int i = 0; i < libNameCount; i++) {
10153            String libName = libs.get(i);
10154            int version = (versions != null && versions.length == libNameCount)
10155                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10156            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10157            if (libPkg != null) {
10158                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10159            }
10160        }
10161    }
10162
10163    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10164        synchronized (mPackages) {
10165            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10166            if (libEntry != null) {
10167                return mPackages.get(libEntry.apk);
10168            }
10169            return null;
10170        }
10171    }
10172
10173    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10174        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10175        if (versionedLib == null) {
10176            return null;
10177        }
10178        return versionedLib.get(version);
10179    }
10180
10181    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10182        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10183                pkg.staticSharedLibName);
10184        if (versionedLib == null) {
10185            return null;
10186        }
10187        int previousLibVersion = -1;
10188        final int versionCount = versionedLib.size();
10189        for (int i = 0; i < versionCount; i++) {
10190            final int libVersion = versionedLib.keyAt(i);
10191            if (libVersion < pkg.staticSharedLibVersion) {
10192                previousLibVersion = Math.max(previousLibVersion, libVersion);
10193            }
10194        }
10195        if (previousLibVersion >= 0) {
10196            return versionedLib.get(previousLibVersion);
10197        }
10198        return null;
10199    }
10200
10201    public void shutdown() {
10202        mPackageUsage.writeNow(mPackages);
10203        mCompilerStats.writeNow();
10204        mDexManager.writePackageDexUsageNow();
10205    }
10206
10207    @Override
10208    public void dumpProfiles(String packageName) {
10209        PackageParser.Package pkg;
10210        synchronized (mPackages) {
10211            pkg = mPackages.get(packageName);
10212            if (pkg == null) {
10213                throw new IllegalArgumentException("Unknown package: " + packageName);
10214            }
10215        }
10216        /* Only the shell, root, or the app user should be able to dump profiles. */
10217        int callingUid = Binder.getCallingUid();
10218        if (callingUid != Process.SHELL_UID &&
10219            callingUid != Process.ROOT_UID &&
10220            callingUid != pkg.applicationInfo.uid) {
10221            throw new SecurityException("dumpProfiles");
10222        }
10223
10224        synchronized (mInstallLock) {
10225            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10226            mArtManagerService.dumpProfiles(pkg);
10227            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10228        }
10229    }
10230
10231    @Override
10232    public void forceDexOpt(String packageName) {
10233        enforceSystemOrRoot("forceDexOpt");
10234
10235        PackageParser.Package pkg;
10236        synchronized (mPackages) {
10237            pkg = mPackages.get(packageName);
10238            if (pkg == null) {
10239                throw new IllegalArgumentException("Unknown package: " + packageName);
10240            }
10241        }
10242
10243        synchronized (mInstallLock) {
10244            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10245
10246            // Whoever is calling forceDexOpt wants a compiled package.
10247            // Don't use profiles since that may cause compilation to be skipped.
10248            final int res = performDexOptInternalWithDependenciesLI(
10249                    pkg,
10250                    new DexoptOptions(packageName,
10251                            getDefaultCompilerFilter(),
10252                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10253
10254            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10255            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10256                throw new IllegalStateException("Failed to dexopt: " + res);
10257            }
10258        }
10259    }
10260
10261    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10262        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10263            Slog.w(TAG, "Unable to update from " + oldPkg.name
10264                    + " to " + newPkg.packageName
10265                    + ": old package not in system partition");
10266            return false;
10267        } else if (mPackages.get(oldPkg.name) != null) {
10268            Slog.w(TAG, "Unable to update from " + oldPkg.name
10269                    + " to " + newPkg.packageName
10270                    + ": old package still exists");
10271            return false;
10272        }
10273        return true;
10274    }
10275
10276    void removeCodePathLI(File codePath) {
10277        if (codePath.isDirectory()) {
10278            try {
10279                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10280            } catch (InstallerException e) {
10281                Slog.w(TAG, "Failed to remove code path", e);
10282            }
10283        } else {
10284            codePath.delete();
10285        }
10286    }
10287
10288    private int[] resolveUserIds(int userId) {
10289        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10290    }
10291
10292    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10293        if (pkg == null) {
10294            Slog.wtf(TAG, "Package was null!", new Throwable());
10295            return;
10296        }
10297        clearAppDataLeafLIF(pkg, userId, flags);
10298        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10299        for (int i = 0; i < childCount; i++) {
10300            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10301        }
10302
10303        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
10304    }
10305
10306    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10307        final PackageSetting ps;
10308        synchronized (mPackages) {
10309            ps = mSettings.mPackages.get(pkg.packageName);
10310        }
10311        for (int realUserId : resolveUserIds(userId)) {
10312            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10313            try {
10314                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10315                        ceDataInode);
10316            } catch (InstallerException e) {
10317                Slog.w(TAG, String.valueOf(e));
10318            }
10319        }
10320    }
10321
10322    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10323        if (pkg == null) {
10324            Slog.wtf(TAG, "Package was null!", new Throwable());
10325            return;
10326        }
10327        destroyAppDataLeafLIF(pkg, userId, flags);
10328        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10329        for (int i = 0; i < childCount; i++) {
10330            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10331        }
10332    }
10333
10334    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10335        final PackageSetting ps;
10336        synchronized (mPackages) {
10337            ps = mSettings.mPackages.get(pkg.packageName);
10338        }
10339        for (int realUserId : resolveUserIds(userId)) {
10340            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10341            try {
10342                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10343                        ceDataInode);
10344            } catch (InstallerException e) {
10345                Slog.w(TAG, String.valueOf(e));
10346            }
10347            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10348        }
10349    }
10350
10351    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10352        if (pkg == null) {
10353            Slog.wtf(TAG, "Package was null!", new Throwable());
10354            return;
10355        }
10356        destroyAppProfilesLeafLIF(pkg);
10357        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10358        for (int i = 0; i < childCount; i++) {
10359            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10360        }
10361    }
10362
10363    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10364        try {
10365            mInstaller.destroyAppProfiles(pkg.packageName);
10366        } catch (InstallerException e) {
10367            Slog.w(TAG, String.valueOf(e));
10368        }
10369    }
10370
10371    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10372        if (pkg == null) {
10373            Slog.wtf(TAG, "Package was null!", new Throwable());
10374            return;
10375        }
10376        mArtManagerService.clearAppProfiles(pkg);
10377        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10378        for (int i = 0; i < childCount; i++) {
10379            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
10380        }
10381    }
10382
10383    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10384            long lastUpdateTime) {
10385        // Set parent install/update time
10386        PackageSetting ps = (PackageSetting) pkg.mExtras;
10387        if (ps != null) {
10388            ps.firstInstallTime = firstInstallTime;
10389            ps.lastUpdateTime = lastUpdateTime;
10390        }
10391        // Set children install/update time
10392        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10393        for (int i = 0; i < childCount; i++) {
10394            PackageParser.Package childPkg = pkg.childPackages.get(i);
10395            ps = (PackageSetting) childPkg.mExtras;
10396            if (ps != null) {
10397                ps.firstInstallTime = firstInstallTime;
10398                ps.lastUpdateTime = lastUpdateTime;
10399            }
10400        }
10401    }
10402
10403    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
10404            SharedLibraryEntry file,
10405            PackageParser.Package changingLib) {
10406        if (file.path != null) {
10407            usesLibraryFiles.add(file.path);
10408            return;
10409        }
10410        PackageParser.Package p = mPackages.get(file.apk);
10411        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10412            // If we are doing this while in the middle of updating a library apk,
10413            // then we need to make sure to use that new apk for determining the
10414            // dependencies here.  (We haven't yet finished committing the new apk
10415            // to the package manager state.)
10416            if (p == null || p.packageName.equals(changingLib.packageName)) {
10417                p = changingLib;
10418            }
10419        }
10420        if (p != null) {
10421            usesLibraryFiles.addAll(p.getAllCodePaths());
10422            if (p.usesLibraryFiles != null) {
10423                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10424            }
10425        }
10426    }
10427
10428    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10429            PackageParser.Package changingLib) throws PackageManagerException {
10430        if (pkg == null) {
10431            return;
10432        }
10433        // The collection used here must maintain the order of addition (so
10434        // that libraries are searched in the correct order) and must have no
10435        // duplicates.
10436        Set<String> usesLibraryFiles = null;
10437        if (pkg.usesLibraries != null) {
10438            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10439                    null, null, pkg.packageName, changingLib, true,
10440                    pkg.applicationInfo.targetSdkVersion, null);
10441        }
10442        if (pkg.usesStaticLibraries != null) {
10443            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10444                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10445                    pkg.packageName, changingLib, true,
10446                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10447        }
10448        if (pkg.usesOptionalLibraries != null) {
10449            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10450                    null, null, pkg.packageName, changingLib, false,
10451                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10452        }
10453        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10454            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10455        } else {
10456            pkg.usesLibraryFiles = null;
10457        }
10458    }
10459
10460    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10461            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10462            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10463            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
10464            throws PackageManagerException {
10465        final int libCount = requestedLibraries.size();
10466        for (int i = 0; i < libCount; i++) {
10467            final String libName = requestedLibraries.get(i);
10468            final int libVersion = requiredVersions != null ? requiredVersions[i]
10469                    : SharedLibraryInfo.VERSION_UNDEFINED;
10470            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10471            if (libEntry == null) {
10472                if (required) {
10473                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10474                            "Package " + packageName + " requires unavailable shared library "
10475                                    + libName + "; failing!");
10476                } else if (DEBUG_SHARED_LIBRARIES) {
10477                    Slog.i(TAG, "Package " + packageName
10478                            + " desires unavailable shared library "
10479                            + libName + "; ignoring!");
10480                }
10481            } else {
10482                if (requiredVersions != null && requiredCertDigests != null) {
10483                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10484                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10485                            "Package " + packageName + " requires unavailable static shared"
10486                                    + " library " + libName + " version "
10487                                    + libEntry.info.getVersion() + "; failing!");
10488                    }
10489
10490                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10491                    if (libPkg == null) {
10492                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10493                                "Package " + packageName + " requires unavailable static shared"
10494                                        + " library; failing!");
10495                    }
10496
10497                    final String[] expectedCertDigests = requiredCertDigests[i];
10498                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10499                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10500                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10501                            : PackageUtils.computeSignaturesSha256Digests(
10502                                    new Signature[]{libPkg.mSignatures[0]});
10503
10504                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10505                    // target O we don't parse the "additional-certificate" tags similarly
10506                    // how we only consider all certs only for apps targeting O (see above).
10507                    // Therefore, the size check is safe to make.
10508                    if (expectedCertDigests.length != libCertDigests.length) {
10509                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10510                                "Package " + packageName + " requires differently signed" +
10511                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10512                    }
10513
10514                    // Use a predictable order as signature order may vary
10515                    Arrays.sort(libCertDigests);
10516                    Arrays.sort(expectedCertDigests);
10517
10518                    final int certCount = libCertDigests.length;
10519                    for (int j = 0; j < certCount; j++) {
10520                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10521                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10522                                    "Package " + packageName + " requires differently signed" +
10523                                            " static shared library; failing!");
10524                        }
10525                    }
10526                }
10527
10528                if (outUsedLibraries == null) {
10529                    // Use LinkedHashSet to preserve the order of files added to
10530                    // usesLibraryFiles while eliminating duplicates.
10531                    outUsedLibraries = new LinkedHashSet<>();
10532                }
10533                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10534            }
10535        }
10536        return outUsedLibraries;
10537    }
10538
10539    private static boolean hasString(List<String> list, List<String> which) {
10540        if (list == null) {
10541            return false;
10542        }
10543        for (int i=list.size()-1; i>=0; i--) {
10544            for (int j=which.size()-1; j>=0; j--) {
10545                if (which.get(j).equals(list.get(i))) {
10546                    return true;
10547                }
10548            }
10549        }
10550        return false;
10551    }
10552
10553    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10554            PackageParser.Package changingPkg) {
10555        ArrayList<PackageParser.Package> res = null;
10556        for (PackageParser.Package pkg : mPackages.values()) {
10557            if (changingPkg != null
10558                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10559                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10560                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10561                            changingPkg.staticSharedLibName)) {
10562                return null;
10563            }
10564            if (res == null) {
10565                res = new ArrayList<>();
10566            }
10567            res.add(pkg);
10568            try {
10569                updateSharedLibrariesLPr(pkg, changingPkg);
10570            } catch (PackageManagerException e) {
10571                // If a system app update or an app and a required lib missing we
10572                // delete the package and for updated system apps keep the data as
10573                // it is better for the user to reinstall than to be in an limbo
10574                // state. Also libs disappearing under an app should never happen
10575                // - just in case.
10576                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10577                    final int flags = pkg.isUpdatedSystemApp()
10578                            ? PackageManager.DELETE_KEEP_DATA : 0;
10579                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10580                            flags , null, true, null);
10581                }
10582                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10583            }
10584        }
10585        return res;
10586    }
10587
10588    /**
10589     * Derive the value of the {@code cpuAbiOverride} based on the provided
10590     * value and an optional stored value from the package settings.
10591     */
10592    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10593        String cpuAbiOverride = null;
10594
10595        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10596            cpuAbiOverride = null;
10597        } else if (abiOverride != null) {
10598            cpuAbiOverride = abiOverride;
10599        } else if (settings != null) {
10600            cpuAbiOverride = settings.cpuAbiOverrideString;
10601        }
10602
10603        return cpuAbiOverride;
10604    }
10605
10606    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10607            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10608                    throws PackageManagerException {
10609        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10610        // If the package has children and this is the first dive in the function
10611        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10612        // whether all packages (parent and children) would be successfully scanned
10613        // before the actual scan since scanning mutates internal state and we want
10614        // to atomically install the package and its children.
10615        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10616            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10617                scanFlags |= SCAN_CHECK_ONLY;
10618            }
10619        } else {
10620            scanFlags &= ~SCAN_CHECK_ONLY;
10621        }
10622
10623        final PackageParser.Package scannedPkg;
10624        try {
10625            // Scan the parent
10626            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10627            // Scan the children
10628            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10629            for (int i = 0; i < childCount; i++) {
10630                PackageParser.Package childPkg = pkg.childPackages.get(i);
10631                scanPackageLI(childPkg, policyFlags,
10632                        scanFlags, currentTime, user);
10633            }
10634        } finally {
10635            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10636        }
10637
10638        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10639            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10640        }
10641
10642        return scannedPkg;
10643    }
10644
10645    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10646            int scanFlags, long currentTime, @Nullable UserHandle user)
10647                    throws PackageManagerException {
10648        boolean success = false;
10649        try {
10650            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10651                    currentTime, user);
10652            success = true;
10653            return res;
10654        } finally {
10655            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10656                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10657                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10658                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10659                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10660            }
10661        }
10662    }
10663
10664    /**
10665     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10666     */
10667    private static boolean apkHasCode(String fileName) {
10668        StrictJarFile jarFile = null;
10669        try {
10670            jarFile = new StrictJarFile(fileName,
10671                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10672            return jarFile.findEntry("classes.dex") != null;
10673        } catch (IOException ignore) {
10674        } finally {
10675            try {
10676                if (jarFile != null) {
10677                    jarFile.close();
10678                }
10679            } catch (IOException ignore) {}
10680        }
10681        return false;
10682    }
10683
10684    /**
10685     * Enforces code policy for the package. This ensures that if an APK has
10686     * declared hasCode="true" in its manifest that the APK actually contains
10687     * code.
10688     *
10689     * @throws PackageManagerException If bytecode could not be found when it should exist
10690     */
10691    private static void assertCodePolicy(PackageParser.Package pkg)
10692            throws PackageManagerException {
10693        final boolean shouldHaveCode =
10694                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10695        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10696            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10697                    "Package " + pkg.baseCodePath + " code is missing");
10698        }
10699
10700        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10701            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10702                final boolean splitShouldHaveCode =
10703                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10704                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10705                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10706                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10707                }
10708            }
10709        }
10710    }
10711
10712    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10713            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10714                    throws PackageManagerException {
10715        if (DEBUG_PACKAGE_SCANNING) {
10716            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10717                Log.d(TAG, "Scanning package " + pkg.packageName);
10718        }
10719
10720        applyPolicy(pkg, policyFlags);
10721
10722        assertPackageIsValid(pkg, policyFlags, scanFlags);
10723
10724        if (Build.IS_DEBUGGABLE &&
10725                pkg.isPrivilegedApp() &&
10726                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10727            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10728        }
10729
10730        // Initialize package source and resource directories
10731        final File scanFile = new File(pkg.codePath);
10732        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10733        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10734
10735        SharedUserSetting suid = null;
10736        PackageSetting pkgSetting = null;
10737
10738        // Getting the package setting may have a side-effect, so if we
10739        // are only checking if scan would succeed, stash a copy of the
10740        // old setting to restore at the end.
10741        PackageSetting nonMutatedPs = null;
10742
10743        // We keep references to the derived CPU Abis from settings in oder to reuse
10744        // them in the case where we're not upgrading or booting for the first time.
10745        String primaryCpuAbiFromSettings = null;
10746        String secondaryCpuAbiFromSettings = null;
10747        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10748
10749        // writer
10750        synchronized (mPackages) {
10751            if (pkg.mSharedUserId != null) {
10752                // SIDE EFFECTS; may potentially allocate a new shared user
10753                suid = mSettings.getSharedUserLPw(
10754                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10755                if (DEBUG_PACKAGE_SCANNING) {
10756                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10757                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10758                                + "): packages=" + suid.packages);
10759                }
10760            }
10761
10762            // Check if we are renaming from an original package name.
10763            PackageSetting origPackage = null;
10764            String realName = null;
10765            if (pkg.mOriginalPackages != null) {
10766                // This package may need to be renamed to a previously
10767                // installed name.  Let's check on that...
10768                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10769                if (pkg.mOriginalPackages.contains(renamed)) {
10770                    // This package had originally been installed as the
10771                    // original name, and we have already taken care of
10772                    // transitioning to the new one.  Just update the new
10773                    // one to continue using the old name.
10774                    realName = pkg.mRealPackage;
10775                    if (!pkg.packageName.equals(renamed)) {
10776                        // Callers into this function may have already taken
10777                        // care of renaming the package; only do it here if
10778                        // it is not already done.
10779                        pkg.setPackageName(renamed);
10780                    }
10781                } else {
10782                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10783                        if ((origPackage = mSettings.getPackageLPr(
10784                                pkg.mOriginalPackages.get(i))) != null) {
10785                            // We do have the package already installed under its
10786                            // original name...  should we use it?
10787                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10788                                // New package is not compatible with original.
10789                                origPackage = null;
10790                                continue;
10791                            } else if (origPackage.sharedUser != null) {
10792                                // Make sure uid is compatible between packages.
10793                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10794                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10795                                            + " to " + pkg.packageName + ": old uid "
10796                                            + origPackage.sharedUser.name
10797                                            + " differs from " + pkg.mSharedUserId);
10798                                    origPackage = null;
10799                                    continue;
10800                                }
10801                                // TODO: Add case when shared user id is added [b/28144775]
10802                            } else {
10803                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10804                                        + pkg.packageName + " to old name " + origPackage.name);
10805                            }
10806                            break;
10807                        }
10808                    }
10809                }
10810            }
10811
10812            if (mTransferedPackages.contains(pkg.packageName)) {
10813                Slog.w(TAG, "Package " + pkg.packageName
10814                        + " was transferred to another, but its .apk remains");
10815            }
10816
10817            // See comments in nonMutatedPs declaration
10818            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10819                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10820                if (foundPs != null) {
10821                    nonMutatedPs = new PackageSetting(foundPs);
10822                }
10823            }
10824
10825            if (!needToDeriveAbi) {
10826                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10827                if (foundPs != null) {
10828                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10829                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10830                } else {
10831                    // when re-adding a system package failed after uninstalling updates.
10832                    needToDeriveAbi = true;
10833                }
10834            }
10835
10836            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10837            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10838                PackageManagerService.reportSettingsProblem(Log.WARN,
10839                        "Package " + pkg.packageName + " shared user changed from "
10840                                + (pkgSetting.sharedUser != null
10841                                        ? pkgSetting.sharedUser.name : "<nothing>")
10842                                + " to "
10843                                + (suid != null ? suid.name : "<nothing>")
10844                                + "; replacing with new");
10845                pkgSetting = null;
10846            }
10847            final PackageSetting oldPkgSetting =
10848                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10849            final PackageSetting disabledPkgSetting =
10850                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10851
10852            String[] usesStaticLibraries = null;
10853            if (pkg.usesStaticLibraries != null) {
10854                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10855                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10856            }
10857
10858            if (pkgSetting == null) {
10859                final String parentPackageName = (pkg.parentPackage != null)
10860                        ? pkg.parentPackage.packageName : null;
10861                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10862                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10863                // REMOVE SharedUserSetting from method; update in a separate call
10864                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10865                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10866                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10867                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10868                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10869                        true /*allowInstall*/, instantApp, virtualPreload,
10870                        parentPackageName, pkg.getChildPackageNames(),
10871                        UserManagerService.getInstance(), usesStaticLibraries,
10872                        pkg.usesStaticLibrariesVersions);
10873                // SIDE EFFECTS; updates system state; move elsewhere
10874                if (origPackage != null) {
10875                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10876                }
10877                mSettings.addUserToSettingLPw(pkgSetting);
10878            } else {
10879                // REMOVE SharedUserSetting from method; update in a separate call.
10880                //
10881                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10882                // secondaryCpuAbi are not known at this point so we always update them
10883                // to null here, only to reset them at a later point.
10884                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10885                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10886                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10887                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10888                        UserManagerService.getInstance(), usesStaticLibraries,
10889                        pkg.usesStaticLibrariesVersions);
10890            }
10891            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10892            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10893
10894            // SIDE EFFECTS; modifies system state; move elsewhere
10895            if (pkgSetting.origPackage != null) {
10896                // If we are first transitioning from an original package,
10897                // fix up the new package's name now.  We need to do this after
10898                // looking up the package under its new name, so getPackageLP
10899                // can take care of fiddling things correctly.
10900                pkg.setPackageName(origPackage.name);
10901
10902                // File a report about this.
10903                String msg = "New package " + pkgSetting.realName
10904                        + " renamed to replace old package " + pkgSetting.name;
10905                reportSettingsProblem(Log.WARN, msg);
10906
10907                // Make a note of it.
10908                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10909                    mTransferedPackages.add(origPackage.name);
10910                }
10911
10912                // No longer need to retain this.
10913                pkgSetting.origPackage = null;
10914            }
10915
10916            // SIDE EFFECTS; modifies system state; move elsewhere
10917            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10918                // Make a note of it.
10919                mTransferedPackages.add(pkg.packageName);
10920            }
10921
10922            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10923                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10924            }
10925
10926            if ((scanFlags & SCAN_BOOTING) == 0
10927                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10928                // Check all shared libraries and map to their actual file path.
10929                // We only do this here for apps not on a system dir, because those
10930                // are the only ones that can fail an install due to this.  We
10931                // will take care of the system apps by updating all of their
10932                // library paths after the scan is done. Also during the initial
10933                // scan don't update any libs as we do this wholesale after all
10934                // apps are scanned to avoid dependency based scanning.
10935                updateSharedLibrariesLPr(pkg, null);
10936            }
10937
10938            if (mFoundPolicyFile) {
10939                SELinuxMMAC.assignSeInfoValue(pkg);
10940            }
10941            pkg.applicationInfo.uid = pkgSetting.appId;
10942            pkg.mExtras = pkgSetting;
10943
10944
10945            // Static shared libs have same package with different versions where
10946            // we internally use a synthetic package name to allow multiple versions
10947            // of the same package, therefore we need to compare signatures against
10948            // the package setting for the latest library version.
10949            PackageSetting signatureCheckPs = pkgSetting;
10950            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10951                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10952                if (libraryEntry != null) {
10953                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10954                }
10955            }
10956
10957            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10958                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10959                    // We just determined the app is signed correctly, so bring
10960                    // over the latest parsed certs.
10961                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10962                } else {
10963                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10964                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10965                                "Package " + pkg.packageName + " upgrade keys do not match the "
10966                                + "previously installed version");
10967                    } else {
10968                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10969                        String msg = "System package " + pkg.packageName
10970                                + " signature changed; retaining data.";
10971                        reportSettingsProblem(Log.WARN, msg);
10972                    }
10973                }
10974            } else {
10975                try {
10976                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10977                    verifySignaturesLP(signatureCheckPs, pkg);
10978                    // We just determined the app is signed correctly, so bring
10979                    // over the latest parsed certs.
10980                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10981                } catch (PackageManagerException e) {
10982                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10983                        throw e;
10984                    }
10985                    // The signature has changed, but this package is in the system
10986                    // image...  let's recover!
10987                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10988                    // However...  if this package is part of a shared user, but it
10989                    // doesn't match the signature of the shared user, let's fail.
10990                    // What this means is that you can't change the signatures
10991                    // associated with an overall shared user, which doesn't seem all
10992                    // that unreasonable.
10993                    if (signatureCheckPs.sharedUser != null) {
10994                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10995                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10996                            throw new PackageManagerException(
10997                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10998                                    "Signature mismatch for shared user: "
10999                                            + pkgSetting.sharedUser);
11000                        }
11001                    }
11002                    // File a report about this.
11003                    String msg = "System package " + pkg.packageName
11004                            + " signature changed; retaining data.";
11005                    reportSettingsProblem(Log.WARN, msg);
11006                }
11007            }
11008
11009            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
11010                // This package wants to adopt ownership of permissions from
11011                // another package.
11012                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
11013                    final String origName = pkg.mAdoptPermissions.get(i);
11014                    final PackageSetting orig = mSettings.getPackageLPr(origName);
11015                    if (orig != null) {
11016                        if (verifyPackageUpdateLPr(orig, pkg)) {
11017                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
11018                                    + pkg.packageName);
11019                            // SIDE EFFECTS; updates permissions system state; move elsewhere
11020                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
11021                        }
11022                    }
11023                }
11024            }
11025        }
11026
11027        pkg.applicationInfo.processName = fixProcessName(
11028                pkg.applicationInfo.packageName,
11029                pkg.applicationInfo.processName);
11030
11031        if (pkg != mPlatformPackage) {
11032            // Get all of our default paths setup
11033            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
11034        }
11035
11036        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
11037
11038        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
11039            if (needToDeriveAbi) {
11040                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
11041                final boolean extractNativeLibs = !pkg.isLibrary();
11042                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
11043                        mAppLib32InstallDir);
11044                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11045
11046                // Some system apps still use directory structure for native libraries
11047                // in which case we might end up not detecting abi solely based on apk
11048                // structure. Try to detect abi based on directory structure.
11049                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
11050                        pkg.applicationInfo.primaryCpuAbi == null) {
11051                    setBundledAppAbisAndRoots(pkg, pkgSetting);
11052                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11053                }
11054            } else {
11055                // This is not a first boot or an upgrade, don't bother deriving the
11056                // ABI during the scan. Instead, trust the value that was stored in the
11057                // package setting.
11058                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
11059                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
11060
11061                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11062
11063                if (DEBUG_ABI_SELECTION) {
11064                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11065                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11066                        pkg.applicationInfo.secondaryCpuAbi);
11067                }
11068            }
11069        } else {
11070            if ((scanFlags & SCAN_MOVE) != 0) {
11071                // We haven't run dex-opt for this move (since we've moved the compiled output too)
11072                // but we already have this packages package info in the PackageSetting. We just
11073                // use that and derive the native library path based on the new codepath.
11074                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11075                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11076            }
11077
11078            // Set native library paths again. For moves, the path will be updated based on the
11079            // ABIs we've determined above. For non-moves, the path will be updated based on the
11080            // ABIs we determined during compilation, but the path will depend on the final
11081            // package path (after the rename away from the stage path).
11082            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11083        }
11084
11085        // This is a special case for the "system" package, where the ABI is
11086        // dictated by the zygote configuration (and init.rc). We should keep track
11087        // of this ABI so that we can deal with "normal" applications that run under
11088        // the same UID correctly.
11089        if (mPlatformPackage == pkg) {
11090            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11091                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11092        }
11093
11094        // If there's a mismatch between the abi-override in the package setting
11095        // and the abiOverride specified for the install. Warn about this because we
11096        // would've already compiled the app without taking the package setting into
11097        // account.
11098        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11099            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11100                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11101                        " for package " + pkg.packageName);
11102            }
11103        }
11104
11105        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11106        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11107        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11108
11109        // Copy the derived override back to the parsed package, so that we can
11110        // update the package settings accordingly.
11111        pkg.cpuAbiOverride = cpuAbiOverride;
11112
11113        if (DEBUG_ABI_SELECTION) {
11114            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11115                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11116                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11117        }
11118
11119        // Push the derived path down into PackageSettings so we know what to
11120        // clean up at uninstall time.
11121        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11122
11123        if (DEBUG_ABI_SELECTION) {
11124            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11125                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11126                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11127        }
11128
11129        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11130        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11131            // We don't do this here during boot because we can do it all
11132            // at once after scanning all existing packages.
11133            //
11134            // We also do this *before* we perform dexopt on this package, so that
11135            // we can avoid redundant dexopts, and also to make sure we've got the
11136            // code and package path correct.
11137            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11138        }
11139
11140        if (mFactoryTest && pkg.requestedPermissions.contains(
11141                android.Manifest.permission.FACTORY_TEST)) {
11142            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11143        }
11144
11145        if (isSystemApp(pkg)) {
11146            pkgSetting.isOrphaned = true;
11147        }
11148
11149        // Take care of first install / last update times.
11150        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11151        if (currentTime != 0) {
11152            if (pkgSetting.firstInstallTime == 0) {
11153                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11154            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11155                pkgSetting.lastUpdateTime = currentTime;
11156            }
11157        } else if (pkgSetting.firstInstallTime == 0) {
11158            // We need *something*.  Take time time stamp of the file.
11159            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11160        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11161            if (scanFileTime != pkgSetting.timeStamp) {
11162                // A package on the system image has changed; consider this
11163                // to be an update.
11164                pkgSetting.lastUpdateTime = scanFileTime;
11165            }
11166        }
11167        pkgSetting.setTimeStamp(scanFileTime);
11168
11169        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11170            if (nonMutatedPs != null) {
11171                synchronized (mPackages) {
11172                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11173                }
11174            }
11175        } else {
11176            final int userId = user == null ? 0 : user.getIdentifier();
11177            // Modify state for the given package setting
11178            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11179                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11180            if (pkgSetting.getInstantApp(userId)) {
11181                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11182            }
11183        }
11184        return pkg;
11185    }
11186
11187    /**
11188     * Applies policy to the parsed package based upon the given policy flags.
11189     * Ensures the package is in a good state.
11190     * <p>
11191     * Implementation detail: This method must NOT have any side effect. It would
11192     * ideally be static, but, it requires locks to read system state.
11193     */
11194    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11195        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11196            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11197            if (pkg.applicationInfo.isDirectBootAware()) {
11198                // we're direct boot aware; set for all components
11199                for (PackageParser.Service s : pkg.services) {
11200                    s.info.encryptionAware = s.info.directBootAware = true;
11201                }
11202                for (PackageParser.Provider p : pkg.providers) {
11203                    p.info.encryptionAware = p.info.directBootAware = true;
11204                }
11205                for (PackageParser.Activity a : pkg.activities) {
11206                    a.info.encryptionAware = a.info.directBootAware = true;
11207                }
11208                for (PackageParser.Activity r : pkg.receivers) {
11209                    r.info.encryptionAware = r.info.directBootAware = true;
11210                }
11211            }
11212            if (compressedFileExists(pkg.codePath)) {
11213                pkg.isStub = true;
11214            }
11215        } else {
11216            // Only allow system apps to be flagged as core apps.
11217            pkg.coreApp = false;
11218            // clear flags not applicable to regular apps
11219            pkg.applicationInfo.privateFlags &=
11220                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11221            pkg.applicationInfo.privateFlags &=
11222                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11223        }
11224        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11225
11226        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11227            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11228        }
11229
11230        if (!isSystemApp(pkg)) {
11231            // Only system apps can use these features.
11232            pkg.mOriginalPackages = null;
11233            pkg.mRealPackage = null;
11234            pkg.mAdoptPermissions = null;
11235        }
11236    }
11237
11238    /**
11239     * Asserts the parsed package is valid according to the given policy. If the
11240     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11241     * <p>
11242     * Implementation detail: This method must NOT have any side effects. It would
11243     * ideally be static, but, it requires locks to read system state.
11244     *
11245     * @throws PackageManagerException If the package fails any of the validation checks
11246     */
11247    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11248            throws PackageManagerException {
11249        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11250            assertCodePolicy(pkg);
11251        }
11252
11253        if (pkg.applicationInfo.getCodePath() == null ||
11254                pkg.applicationInfo.getResourcePath() == null) {
11255            // Bail out. The resource and code paths haven't been set.
11256            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11257                    "Code and resource paths haven't been set correctly");
11258        }
11259
11260        // Make sure we're not adding any bogus keyset info
11261        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11262        ksms.assertScannedPackageValid(pkg);
11263
11264        synchronized (mPackages) {
11265            // The special "android" package can only be defined once
11266            if (pkg.packageName.equals("android")) {
11267                if (mAndroidApplication != null) {
11268                    Slog.w(TAG, "*************************************************");
11269                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11270                    Slog.w(TAG, " codePath=" + pkg.codePath);
11271                    Slog.w(TAG, "*************************************************");
11272                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11273                            "Core android package being redefined.  Skipping.");
11274                }
11275            }
11276
11277            // A package name must be unique; don't allow duplicates
11278            if (mPackages.containsKey(pkg.packageName)) {
11279                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11280                        "Application package " + pkg.packageName
11281                        + " already installed.  Skipping duplicate.");
11282            }
11283
11284            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11285                // Static libs have a synthetic package name containing the version
11286                // but we still want the base name to be unique.
11287                if (mPackages.containsKey(pkg.manifestPackageName)) {
11288                    throw new PackageManagerException(
11289                            "Duplicate static shared lib provider package");
11290                }
11291
11292                // Static shared libraries should have at least O target SDK
11293                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11294                    throw new PackageManagerException(
11295                            "Packages declaring static-shared libs must target O SDK or higher");
11296                }
11297
11298                // Package declaring static a shared lib cannot be instant apps
11299                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11300                    throw new PackageManagerException(
11301                            "Packages declaring static-shared libs cannot be instant apps");
11302                }
11303
11304                // Package declaring static a shared lib cannot be renamed since the package
11305                // name is synthetic and apps can't code around package manager internals.
11306                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11307                    throw new PackageManagerException(
11308                            "Packages declaring static-shared libs cannot be renamed");
11309                }
11310
11311                // Package declaring static a shared lib cannot declare child packages
11312                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11313                    throw new PackageManagerException(
11314                            "Packages declaring static-shared libs cannot have child packages");
11315                }
11316
11317                // Package declaring static a shared lib cannot declare dynamic libs
11318                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11319                    throw new PackageManagerException(
11320                            "Packages declaring static-shared libs cannot declare dynamic libs");
11321                }
11322
11323                // Package declaring static a shared lib cannot declare shared users
11324                if (pkg.mSharedUserId != null) {
11325                    throw new PackageManagerException(
11326                            "Packages declaring static-shared libs cannot declare shared users");
11327                }
11328
11329                // Static shared libs cannot declare activities
11330                if (!pkg.activities.isEmpty()) {
11331                    throw new PackageManagerException(
11332                            "Static shared libs cannot declare activities");
11333                }
11334
11335                // Static shared libs cannot declare services
11336                if (!pkg.services.isEmpty()) {
11337                    throw new PackageManagerException(
11338                            "Static shared libs cannot declare services");
11339                }
11340
11341                // Static shared libs cannot declare providers
11342                if (!pkg.providers.isEmpty()) {
11343                    throw new PackageManagerException(
11344                            "Static shared libs cannot declare content providers");
11345                }
11346
11347                // Static shared libs cannot declare receivers
11348                if (!pkg.receivers.isEmpty()) {
11349                    throw new PackageManagerException(
11350                            "Static shared libs cannot declare broadcast receivers");
11351                }
11352
11353                // Static shared libs cannot declare permission groups
11354                if (!pkg.permissionGroups.isEmpty()) {
11355                    throw new PackageManagerException(
11356                            "Static shared libs cannot declare permission groups");
11357                }
11358
11359                // Static shared libs cannot declare permissions
11360                if (!pkg.permissions.isEmpty()) {
11361                    throw new PackageManagerException(
11362                            "Static shared libs cannot declare permissions");
11363                }
11364
11365                // Static shared libs cannot declare protected broadcasts
11366                if (pkg.protectedBroadcasts != null) {
11367                    throw new PackageManagerException(
11368                            "Static shared libs cannot declare protected broadcasts");
11369                }
11370
11371                // Static shared libs cannot be overlay targets
11372                if (pkg.mOverlayTarget != null) {
11373                    throw new PackageManagerException(
11374                            "Static shared libs cannot be overlay targets");
11375                }
11376
11377                // The version codes must be ordered as lib versions
11378                int minVersionCode = Integer.MIN_VALUE;
11379                int maxVersionCode = Integer.MAX_VALUE;
11380
11381                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11382                        pkg.staticSharedLibName);
11383                if (versionedLib != null) {
11384                    final int versionCount = versionedLib.size();
11385                    for (int i = 0; i < versionCount; i++) {
11386                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11387                        final int libVersionCode = libInfo.getDeclaringPackage()
11388                                .getVersionCode();
11389                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11390                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11391                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11392                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11393                        } else {
11394                            minVersionCode = maxVersionCode = libVersionCode;
11395                            break;
11396                        }
11397                    }
11398                }
11399                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11400                    throw new PackageManagerException("Static shared"
11401                            + " lib version codes must be ordered as lib versions");
11402                }
11403            }
11404
11405            // Only privileged apps and updated privileged apps can add child packages.
11406            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11407                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11408                    throw new PackageManagerException("Only privileged apps can add child "
11409                            + "packages. Ignoring package " + pkg.packageName);
11410                }
11411                final int childCount = pkg.childPackages.size();
11412                for (int i = 0; i < childCount; i++) {
11413                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11414                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11415                            childPkg.packageName)) {
11416                        throw new PackageManagerException("Can't override child of "
11417                                + "another disabled app. Ignoring package " + pkg.packageName);
11418                    }
11419                }
11420            }
11421
11422            // If we're only installing presumed-existing packages, require that the
11423            // scanned APK is both already known and at the path previously established
11424            // for it.  Previously unknown packages we pick up normally, but if we have an
11425            // a priori expectation about this package's install presence, enforce it.
11426            // With a singular exception for new system packages. When an OTA contains
11427            // a new system package, we allow the codepath to change from a system location
11428            // to the user-installed location. If we don't allow this change, any newer,
11429            // user-installed version of the application will be ignored.
11430            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11431                if (mExpectingBetter.containsKey(pkg.packageName)) {
11432                    logCriticalInfo(Log.WARN,
11433                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11434                } else {
11435                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11436                    if (known != null) {
11437                        if (DEBUG_PACKAGE_SCANNING) {
11438                            Log.d(TAG, "Examining " + pkg.codePath
11439                                    + " and requiring known paths " + known.codePathString
11440                                    + " & " + known.resourcePathString);
11441                        }
11442                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11443                                || !pkg.applicationInfo.getResourcePath().equals(
11444                                        known.resourcePathString)) {
11445                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11446                                    "Application package " + pkg.packageName
11447                                    + " found at " + pkg.applicationInfo.getCodePath()
11448                                    + " but expected at " + known.codePathString
11449                                    + "; ignoring.");
11450                        }
11451                    } else {
11452                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11453                                "Application package " + pkg.packageName
11454                                + " not found; ignoring.");
11455                    }
11456                }
11457            }
11458
11459            // Verify that this new package doesn't have any content providers
11460            // that conflict with existing packages.  Only do this if the
11461            // package isn't already installed, since we don't want to break
11462            // things that are installed.
11463            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11464                final int N = pkg.providers.size();
11465                int i;
11466                for (i=0; i<N; i++) {
11467                    PackageParser.Provider p = pkg.providers.get(i);
11468                    if (p.info.authority != null) {
11469                        String names[] = p.info.authority.split(";");
11470                        for (int j = 0; j < names.length; j++) {
11471                            if (mProvidersByAuthority.containsKey(names[j])) {
11472                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11473                                final String otherPackageName =
11474                                        ((other != null && other.getComponentName() != null) ?
11475                                                other.getComponentName().getPackageName() : "?");
11476                                throw new PackageManagerException(
11477                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11478                                        "Can't install because provider name " + names[j]
11479                                                + " (in package " + pkg.applicationInfo.packageName
11480                                                + ") is already used by " + otherPackageName);
11481                            }
11482                        }
11483                    }
11484                }
11485            }
11486        }
11487    }
11488
11489    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11490            int type, String declaringPackageName, int declaringVersionCode) {
11491        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11492        if (versionedLib == null) {
11493            versionedLib = new SparseArray<>();
11494            mSharedLibraries.put(name, versionedLib);
11495            if (type == SharedLibraryInfo.TYPE_STATIC) {
11496                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11497            }
11498        } else if (versionedLib.indexOfKey(version) >= 0) {
11499            return false;
11500        }
11501        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11502                version, type, declaringPackageName, declaringVersionCode);
11503        versionedLib.put(version, libEntry);
11504        return true;
11505    }
11506
11507    private boolean removeSharedLibraryLPw(String name, int version) {
11508        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11509        if (versionedLib == null) {
11510            return false;
11511        }
11512        final int libIdx = versionedLib.indexOfKey(version);
11513        if (libIdx < 0) {
11514            return false;
11515        }
11516        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11517        versionedLib.remove(version);
11518        if (versionedLib.size() <= 0) {
11519            mSharedLibraries.remove(name);
11520            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11521                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11522                        .getPackageName());
11523            }
11524        }
11525        return true;
11526    }
11527
11528    /**
11529     * Adds a scanned package to the system. When this method is finished, the package will
11530     * be available for query, resolution, etc...
11531     */
11532    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11533            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11534        final String pkgName = pkg.packageName;
11535        if (mCustomResolverComponentName != null &&
11536                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11537            setUpCustomResolverActivity(pkg);
11538        }
11539
11540        if (pkg.packageName.equals("android")) {
11541            synchronized (mPackages) {
11542                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11543                    // Set up information for our fall-back user intent resolution activity.
11544                    mPlatformPackage = pkg;
11545                    pkg.mVersionCode = mSdkVersion;
11546                    mAndroidApplication = pkg.applicationInfo;
11547                    if (!mResolverReplaced) {
11548                        mResolveActivity.applicationInfo = mAndroidApplication;
11549                        mResolveActivity.name = ResolverActivity.class.getName();
11550                        mResolveActivity.packageName = mAndroidApplication.packageName;
11551                        mResolveActivity.processName = "system:ui";
11552                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11553                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11554                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11555                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11556                        mResolveActivity.exported = true;
11557                        mResolveActivity.enabled = true;
11558                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11559                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11560                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11561                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11562                                | ActivityInfo.CONFIG_ORIENTATION
11563                                | ActivityInfo.CONFIG_KEYBOARD
11564                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11565                        mResolveInfo.activityInfo = mResolveActivity;
11566                        mResolveInfo.priority = 0;
11567                        mResolveInfo.preferredOrder = 0;
11568                        mResolveInfo.match = 0;
11569                        mResolveComponentName = new ComponentName(
11570                                mAndroidApplication.packageName, mResolveActivity.name);
11571                    }
11572                }
11573            }
11574        }
11575
11576        ArrayList<PackageParser.Package> clientLibPkgs = null;
11577        // writer
11578        synchronized (mPackages) {
11579            boolean hasStaticSharedLibs = false;
11580
11581            // Any app can add new static shared libraries
11582            if (pkg.staticSharedLibName != null) {
11583                // Static shared libs don't allow renaming as they have synthetic package
11584                // names to allow install of multiple versions, so use name from manifest.
11585                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11586                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11587                        pkg.manifestPackageName, pkg.mVersionCode)) {
11588                    hasStaticSharedLibs = true;
11589                } else {
11590                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11591                                + pkg.staticSharedLibName + " already exists; skipping");
11592                }
11593                // Static shared libs cannot be updated once installed since they
11594                // use synthetic package name which includes the version code, so
11595                // not need to update other packages's shared lib dependencies.
11596            }
11597
11598            if (!hasStaticSharedLibs
11599                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11600                // Only system apps can add new dynamic shared libraries.
11601                if (pkg.libraryNames != null) {
11602                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11603                        String name = pkg.libraryNames.get(i);
11604                        boolean allowed = false;
11605                        if (pkg.isUpdatedSystemApp()) {
11606                            // New library entries can only be added through the
11607                            // system image.  This is important to get rid of a lot
11608                            // of nasty edge cases: for example if we allowed a non-
11609                            // system update of the app to add a library, then uninstalling
11610                            // the update would make the library go away, and assumptions
11611                            // we made such as through app install filtering would now
11612                            // have allowed apps on the device which aren't compatible
11613                            // with it.  Better to just have the restriction here, be
11614                            // conservative, and create many fewer cases that can negatively
11615                            // impact the user experience.
11616                            final PackageSetting sysPs = mSettings
11617                                    .getDisabledSystemPkgLPr(pkg.packageName);
11618                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11619                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11620                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11621                                        allowed = true;
11622                                        break;
11623                                    }
11624                                }
11625                            }
11626                        } else {
11627                            allowed = true;
11628                        }
11629                        if (allowed) {
11630                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11631                                    SharedLibraryInfo.VERSION_UNDEFINED,
11632                                    SharedLibraryInfo.TYPE_DYNAMIC,
11633                                    pkg.packageName, pkg.mVersionCode)) {
11634                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11635                                        + name + " already exists; skipping");
11636                            }
11637                        } else {
11638                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11639                                    + name + " that is not declared on system image; skipping");
11640                        }
11641                    }
11642
11643                    if ((scanFlags & SCAN_BOOTING) == 0) {
11644                        // If we are not booting, we need to update any applications
11645                        // that are clients of our shared library.  If we are booting,
11646                        // this will all be done once the scan is complete.
11647                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11648                    }
11649                }
11650            }
11651        }
11652
11653        if ((scanFlags & SCAN_BOOTING) != 0) {
11654            // No apps can run during boot scan, so they don't need to be frozen
11655        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11656            // Caller asked to not kill app, so it's probably not frozen
11657        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11658            // Caller asked us to ignore frozen check for some reason; they
11659            // probably didn't know the package name
11660        } else {
11661            // We're doing major surgery on this package, so it better be frozen
11662            // right now to keep it from launching
11663            checkPackageFrozen(pkgName);
11664        }
11665
11666        // Also need to kill any apps that are dependent on the library.
11667        if (clientLibPkgs != null) {
11668            for (int i=0; i<clientLibPkgs.size(); i++) {
11669                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11670                killApplication(clientPkg.applicationInfo.packageName,
11671                        clientPkg.applicationInfo.uid, "update lib");
11672            }
11673        }
11674
11675        // writer
11676        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11677
11678        synchronized (mPackages) {
11679            // We don't expect installation to fail beyond this point
11680
11681            // Add the new setting to mSettings
11682            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11683            // Add the new setting to mPackages
11684            mPackages.put(pkg.applicationInfo.packageName, pkg);
11685            // Make sure we don't accidentally delete its data.
11686            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11687            while (iter.hasNext()) {
11688                PackageCleanItem item = iter.next();
11689                if (pkgName.equals(item.packageName)) {
11690                    iter.remove();
11691                }
11692            }
11693
11694            // Add the package's KeySets to the global KeySetManagerService
11695            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11696            ksms.addScannedPackageLPw(pkg);
11697
11698            int N = pkg.providers.size();
11699            StringBuilder r = null;
11700            int i;
11701            for (i=0; i<N; i++) {
11702                PackageParser.Provider p = pkg.providers.get(i);
11703                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11704                        p.info.processName);
11705                mProviders.addProvider(p);
11706                p.syncable = p.info.isSyncable;
11707                if (p.info.authority != null) {
11708                    String names[] = p.info.authority.split(";");
11709                    p.info.authority = null;
11710                    for (int j = 0; j < names.length; j++) {
11711                        if (j == 1 && p.syncable) {
11712                            // We only want the first authority for a provider to possibly be
11713                            // syncable, so if we already added this provider using a different
11714                            // authority clear the syncable flag. We copy the provider before
11715                            // changing it because the mProviders object contains a reference
11716                            // to a provider that we don't want to change.
11717                            // Only do this for the second authority since the resulting provider
11718                            // object can be the same for all future authorities for this provider.
11719                            p = new PackageParser.Provider(p);
11720                            p.syncable = false;
11721                        }
11722                        if (!mProvidersByAuthority.containsKey(names[j])) {
11723                            mProvidersByAuthority.put(names[j], p);
11724                            if (p.info.authority == null) {
11725                                p.info.authority = names[j];
11726                            } else {
11727                                p.info.authority = p.info.authority + ";" + names[j];
11728                            }
11729                            if (DEBUG_PACKAGE_SCANNING) {
11730                                if (chatty)
11731                                    Log.d(TAG, "Registered content provider: " + names[j]
11732                                            + ", className = " + p.info.name + ", isSyncable = "
11733                                            + p.info.isSyncable);
11734                            }
11735                        } else {
11736                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11737                            Slog.w(TAG, "Skipping provider name " + names[j] +
11738                                    " (in package " + pkg.applicationInfo.packageName +
11739                                    "): name already used by "
11740                                    + ((other != null && other.getComponentName() != null)
11741                                            ? other.getComponentName().getPackageName() : "?"));
11742                        }
11743                    }
11744                }
11745                if (chatty) {
11746                    if (r == null) {
11747                        r = new StringBuilder(256);
11748                    } else {
11749                        r.append(' ');
11750                    }
11751                    r.append(p.info.name);
11752                }
11753            }
11754            if (r != null) {
11755                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11756            }
11757
11758            N = pkg.services.size();
11759            r = null;
11760            for (i=0; i<N; i++) {
11761                PackageParser.Service s = pkg.services.get(i);
11762                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11763                        s.info.processName);
11764                mServices.addService(s);
11765                if (chatty) {
11766                    if (r == null) {
11767                        r = new StringBuilder(256);
11768                    } else {
11769                        r.append(' ');
11770                    }
11771                    r.append(s.info.name);
11772                }
11773            }
11774            if (r != null) {
11775                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11776            }
11777
11778            N = pkg.receivers.size();
11779            r = null;
11780            for (i=0; i<N; i++) {
11781                PackageParser.Activity a = pkg.receivers.get(i);
11782                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11783                        a.info.processName);
11784                mReceivers.addActivity(a, "receiver");
11785                if (chatty) {
11786                    if (r == null) {
11787                        r = new StringBuilder(256);
11788                    } else {
11789                        r.append(' ');
11790                    }
11791                    r.append(a.info.name);
11792                }
11793            }
11794            if (r != null) {
11795                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11796            }
11797
11798            N = pkg.activities.size();
11799            r = null;
11800            for (i=0; i<N; i++) {
11801                PackageParser.Activity a = pkg.activities.get(i);
11802                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11803                        a.info.processName);
11804                mActivities.addActivity(a, "activity");
11805                if (chatty) {
11806                    if (r == null) {
11807                        r = new StringBuilder(256);
11808                    } else {
11809                        r.append(' ');
11810                    }
11811                    r.append(a.info.name);
11812                }
11813            }
11814            if (r != null) {
11815                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11816            }
11817
11818            N = pkg.permissionGroups.size();
11819            r = null;
11820            for (i=0; i<N; i++) {
11821                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11822                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11823                final String curPackageName = cur == null ? null : cur.info.packageName;
11824                // Dont allow ephemeral apps to define new permission groups.
11825                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11826                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11827                            + pg.info.packageName
11828                            + " ignored: instant apps cannot define new permission groups.");
11829                    continue;
11830                }
11831                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11832                if (cur == null || isPackageUpdate) {
11833                    mPermissionGroups.put(pg.info.name, pg);
11834                    if (chatty) {
11835                        if (r == null) {
11836                            r = new StringBuilder(256);
11837                        } else {
11838                            r.append(' ');
11839                        }
11840                        if (isPackageUpdate) {
11841                            r.append("UPD:");
11842                        }
11843                        r.append(pg.info.name);
11844                    }
11845                } else {
11846                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11847                            + pg.info.packageName + " ignored: original from "
11848                            + cur.info.packageName);
11849                    if (chatty) {
11850                        if (r == null) {
11851                            r = new StringBuilder(256);
11852                        } else {
11853                            r.append(' ');
11854                        }
11855                        r.append("DUP:");
11856                        r.append(pg.info.name);
11857                    }
11858                }
11859            }
11860            if (r != null) {
11861                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11862            }
11863
11864            N = pkg.permissions.size();
11865            r = null;
11866            for (i=0; i<N; i++) {
11867                PackageParser.Permission p = pkg.permissions.get(i);
11868
11869                // Dont allow ephemeral apps to define new permissions.
11870                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11871                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11872                            + p.info.packageName
11873                            + " ignored: instant apps cannot define new permissions.");
11874                    continue;
11875                }
11876
11877                // Assume by default that we did not install this permission into the system.
11878                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11879
11880                // Now that permission groups have a special meaning, we ignore permission
11881                // groups for legacy apps to prevent unexpected behavior. In particular,
11882                // permissions for one app being granted to someone just because they happen
11883                // to be in a group defined by another app (before this had no implications).
11884                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11885                    p.group = mPermissionGroups.get(p.info.group);
11886                    // Warn for a permission in an unknown group.
11887                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11888                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11889                                + p.info.packageName + " in an unknown group " + p.info.group);
11890                    }
11891                }
11892
11893                ArrayMap<String, BasePermission> permissionMap =
11894                        p.tree ? mSettings.mPermissionTrees
11895                                : mSettings.mPermissions;
11896                BasePermission bp = permissionMap.get(p.info.name);
11897
11898                // Allow system apps to redefine non-system permissions
11899                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11900                    final boolean currentOwnerIsSystem = (bp.perm != null
11901                            && isSystemApp(bp.perm.owner));
11902                    if (isSystemApp(p.owner)) {
11903                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11904                            // It's a built-in permission and no owner, take ownership now
11905                            bp.packageSetting = pkgSetting;
11906                            bp.perm = p;
11907                            bp.uid = pkg.applicationInfo.uid;
11908                            bp.sourcePackage = p.info.packageName;
11909                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11910                        } else if (!currentOwnerIsSystem) {
11911                            String msg = "New decl " + p.owner + " of permission  "
11912                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11913                            reportSettingsProblem(Log.WARN, msg);
11914                            bp = null;
11915                        }
11916                    }
11917                }
11918
11919                if (bp == null) {
11920                    bp = new BasePermission(p.info.name, p.info.packageName,
11921                            BasePermission.TYPE_NORMAL);
11922                    permissionMap.put(p.info.name, bp);
11923                }
11924
11925                if (bp.perm == null) {
11926                    if (bp.sourcePackage == null
11927                            || bp.sourcePackage.equals(p.info.packageName)) {
11928                        BasePermission tree = findPermissionTreeLP(p.info.name);
11929                        if (tree == null
11930                                || tree.sourcePackage.equals(p.info.packageName)) {
11931                            bp.packageSetting = pkgSetting;
11932                            bp.perm = p;
11933                            bp.uid = pkg.applicationInfo.uid;
11934                            bp.sourcePackage = p.info.packageName;
11935                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11936                            if (chatty) {
11937                                if (r == null) {
11938                                    r = new StringBuilder(256);
11939                                } else {
11940                                    r.append(' ');
11941                                }
11942                                r.append(p.info.name);
11943                            }
11944                        } else {
11945                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11946                                    + p.info.packageName + " ignored: base tree "
11947                                    + tree.name + " is from package "
11948                                    + tree.sourcePackage);
11949                        }
11950                    } else {
11951                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11952                                + p.info.packageName + " ignored: original from "
11953                                + bp.sourcePackage);
11954                    }
11955                } else if (chatty) {
11956                    if (r == null) {
11957                        r = new StringBuilder(256);
11958                    } else {
11959                        r.append(' ');
11960                    }
11961                    r.append("DUP:");
11962                    r.append(p.info.name);
11963                }
11964                if (bp.perm == p) {
11965                    bp.protectionLevel = p.info.protectionLevel;
11966                }
11967            }
11968
11969            if (r != null) {
11970                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11971            }
11972
11973            N = pkg.instrumentation.size();
11974            r = null;
11975            for (i=0; i<N; i++) {
11976                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11977                a.info.packageName = pkg.applicationInfo.packageName;
11978                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11979                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11980                a.info.splitNames = pkg.splitNames;
11981                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11982                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11983                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11984                a.info.dataDir = pkg.applicationInfo.dataDir;
11985                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11986                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11987                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11988                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11989                mInstrumentation.put(a.getComponentName(), a);
11990                if (chatty) {
11991                    if (r == null) {
11992                        r = new StringBuilder(256);
11993                    } else {
11994                        r.append(' ');
11995                    }
11996                    r.append(a.info.name);
11997                }
11998            }
11999            if (r != null) {
12000                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
12001            }
12002
12003            if (pkg.protectedBroadcasts != null) {
12004                N = pkg.protectedBroadcasts.size();
12005                synchronized (mProtectedBroadcasts) {
12006                    for (i = 0; i < N; i++) {
12007                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
12008                    }
12009                }
12010            }
12011        }
12012
12013        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12014    }
12015
12016    /**
12017     * Derive the ABI of a non-system package located at {@code scanFile}. This information
12018     * is derived purely on the basis of the contents of {@code scanFile} and
12019     * {@code cpuAbiOverride}.
12020     *
12021     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
12022     */
12023    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
12024                                 String cpuAbiOverride, boolean extractLibs,
12025                                 File appLib32InstallDir)
12026            throws PackageManagerException {
12027        // Give ourselves some initial paths; we'll come back for another
12028        // pass once we've determined ABI below.
12029        setNativeLibraryPaths(pkg, appLib32InstallDir);
12030
12031        // We would never need to extract libs for forward-locked and external packages,
12032        // since the container service will do it for us. We shouldn't attempt to
12033        // extract libs from system app when it was not updated.
12034        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
12035                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
12036            extractLibs = false;
12037        }
12038
12039        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
12040        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
12041
12042        NativeLibraryHelper.Handle handle = null;
12043        try {
12044            handle = NativeLibraryHelper.Handle.create(pkg);
12045            // TODO(multiArch): This can be null for apps that didn't go through the
12046            // usual installation process. We can calculate it again, like we
12047            // do during install time.
12048            //
12049            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
12050            // unnecessary.
12051            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
12052
12053            // Null out the abis so that they can be recalculated.
12054            pkg.applicationInfo.primaryCpuAbi = null;
12055            pkg.applicationInfo.secondaryCpuAbi = null;
12056            if (isMultiArch(pkg.applicationInfo)) {
12057                // Warn if we've set an abiOverride for multi-lib packages..
12058                // By definition, we need to copy both 32 and 64 bit libraries for
12059                // such packages.
12060                if (pkg.cpuAbiOverride != null
12061                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
12062                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
12063                }
12064
12065                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
12066                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
12067                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
12068                    if (extractLibs) {
12069                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12070                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12071                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12072                                useIsaSpecificSubdirs);
12073                    } else {
12074                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12075                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12076                    }
12077                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12078                }
12079
12080                // Shared library native code should be in the APK zip aligned
12081                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12082                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12083                            "Shared library native lib extraction not supported");
12084                }
12085
12086                maybeThrowExceptionForMultiArchCopy(
12087                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12088
12089                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12090                    if (extractLibs) {
12091                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12092                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12093                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12094                                useIsaSpecificSubdirs);
12095                    } else {
12096                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12097                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12098                    }
12099                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12100                }
12101
12102                maybeThrowExceptionForMultiArchCopy(
12103                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12104
12105                if (abi64 >= 0) {
12106                    // Shared library native libs should be in the APK zip aligned
12107                    if (extractLibs && pkg.isLibrary()) {
12108                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12109                                "Shared library native lib extraction not supported");
12110                    }
12111                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12112                }
12113
12114                if (abi32 >= 0) {
12115                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12116                    if (abi64 >= 0) {
12117                        if (pkg.use32bitAbi) {
12118                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12119                            pkg.applicationInfo.primaryCpuAbi = abi;
12120                        } else {
12121                            pkg.applicationInfo.secondaryCpuAbi = abi;
12122                        }
12123                    } else {
12124                        pkg.applicationInfo.primaryCpuAbi = abi;
12125                    }
12126                }
12127            } else {
12128                String[] abiList = (cpuAbiOverride != null) ?
12129                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12130
12131                // Enable gross and lame hacks for apps that are built with old
12132                // SDK tools. We must scan their APKs for renderscript bitcode and
12133                // not launch them if it's present. Don't bother checking on devices
12134                // that don't have 64 bit support.
12135                boolean needsRenderScriptOverride = false;
12136                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12137                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12138                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12139                    needsRenderScriptOverride = true;
12140                }
12141
12142                final int copyRet;
12143                if (extractLibs) {
12144                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12145                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12146                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12147                } else {
12148                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12149                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12150                }
12151                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12152
12153                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12154                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12155                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12156                }
12157
12158                if (copyRet >= 0) {
12159                    // Shared libraries that have native libs must be multi-architecture
12160                    if (pkg.isLibrary()) {
12161                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12162                                "Shared library with native libs must be multiarch");
12163                    }
12164                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12165                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12166                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12167                } else if (needsRenderScriptOverride) {
12168                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12169                }
12170            }
12171        } catch (IOException ioe) {
12172            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12173        } finally {
12174            IoUtils.closeQuietly(handle);
12175        }
12176
12177        // Now that we've calculated the ABIs and determined if it's an internal app,
12178        // we will go ahead and populate the nativeLibraryPath.
12179        setNativeLibraryPaths(pkg, appLib32InstallDir);
12180    }
12181
12182    /**
12183     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12184     * i.e, so that all packages can be run inside a single process if required.
12185     *
12186     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12187     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12188     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12189     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12190     * updating a package that belongs to a shared user.
12191     *
12192     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12193     * adds unnecessary complexity.
12194     */
12195    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12196            PackageParser.Package scannedPackage) {
12197        String requiredInstructionSet = null;
12198        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12199            requiredInstructionSet = VMRuntime.getInstructionSet(
12200                     scannedPackage.applicationInfo.primaryCpuAbi);
12201        }
12202
12203        PackageSetting requirer = null;
12204        for (PackageSetting ps : packagesForUser) {
12205            // If packagesForUser contains scannedPackage, we skip it. This will happen
12206            // when scannedPackage is an update of an existing package. Without this check,
12207            // we will never be able to change the ABI of any package belonging to a shared
12208            // user, even if it's compatible with other packages.
12209            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12210                if (ps.primaryCpuAbiString == null) {
12211                    continue;
12212                }
12213
12214                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12215                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12216                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12217                    // this but there's not much we can do.
12218                    String errorMessage = "Instruction set mismatch, "
12219                            + ((requirer == null) ? "[caller]" : requirer)
12220                            + " requires " + requiredInstructionSet + " whereas " + ps
12221                            + " requires " + instructionSet;
12222                    Slog.w(TAG, errorMessage);
12223                }
12224
12225                if (requiredInstructionSet == null) {
12226                    requiredInstructionSet = instructionSet;
12227                    requirer = ps;
12228                }
12229            }
12230        }
12231
12232        if (requiredInstructionSet != null) {
12233            String adjustedAbi;
12234            if (requirer != null) {
12235                // requirer != null implies that either scannedPackage was null or that scannedPackage
12236                // did not require an ABI, in which case we have to adjust scannedPackage to match
12237                // the ABI of the set (which is the same as requirer's ABI)
12238                adjustedAbi = requirer.primaryCpuAbiString;
12239                if (scannedPackage != null) {
12240                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12241                }
12242            } else {
12243                // requirer == null implies that we're updating all ABIs in the set to
12244                // match scannedPackage.
12245                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12246            }
12247
12248            for (PackageSetting ps : packagesForUser) {
12249                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12250                    if (ps.primaryCpuAbiString != null) {
12251                        continue;
12252                    }
12253
12254                    ps.primaryCpuAbiString = adjustedAbi;
12255                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12256                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12257                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12258                        if (DEBUG_ABI_SELECTION) {
12259                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12260                                    + " (requirer="
12261                                    + (requirer != null ? requirer.pkg : "null")
12262                                    + ", scannedPackage="
12263                                    + (scannedPackage != null ? scannedPackage : "null")
12264                                    + ")");
12265                        }
12266                        try {
12267                            mInstaller.rmdex(ps.codePathString,
12268                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12269                        } catch (InstallerException ignored) {
12270                        }
12271                    }
12272                }
12273            }
12274        }
12275    }
12276
12277    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12278        synchronized (mPackages) {
12279            mResolverReplaced = true;
12280            // Set up information for custom user intent resolution activity.
12281            mResolveActivity.applicationInfo = pkg.applicationInfo;
12282            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12283            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12284            mResolveActivity.processName = pkg.applicationInfo.packageName;
12285            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12286            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12287                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12288            mResolveActivity.theme = 0;
12289            mResolveActivity.exported = true;
12290            mResolveActivity.enabled = true;
12291            mResolveInfo.activityInfo = mResolveActivity;
12292            mResolveInfo.priority = 0;
12293            mResolveInfo.preferredOrder = 0;
12294            mResolveInfo.match = 0;
12295            mResolveComponentName = mCustomResolverComponentName;
12296            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12297                    mResolveComponentName);
12298        }
12299    }
12300
12301    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12302        if (installerActivity == null) {
12303            if (DEBUG_EPHEMERAL) {
12304                Slog.d(TAG, "Clear ephemeral installer activity");
12305            }
12306            mInstantAppInstallerActivity = null;
12307            return;
12308        }
12309
12310        if (DEBUG_EPHEMERAL) {
12311            Slog.d(TAG, "Set ephemeral installer activity: "
12312                    + installerActivity.getComponentName());
12313        }
12314        // Set up information for ephemeral installer activity
12315        mInstantAppInstallerActivity = installerActivity;
12316        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12317                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12318        mInstantAppInstallerActivity.exported = true;
12319        mInstantAppInstallerActivity.enabled = true;
12320        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12321        mInstantAppInstallerInfo.priority = 0;
12322        mInstantAppInstallerInfo.preferredOrder = 1;
12323        mInstantAppInstallerInfo.isDefault = true;
12324        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12325                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12326    }
12327
12328    private static String calculateBundledApkRoot(final String codePathString) {
12329        final File codePath = new File(codePathString);
12330        final File codeRoot;
12331        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12332            codeRoot = Environment.getRootDirectory();
12333        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12334            codeRoot = Environment.getOemDirectory();
12335        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12336            codeRoot = Environment.getVendorDirectory();
12337        } else {
12338            // Unrecognized code path; take its top real segment as the apk root:
12339            // e.g. /something/app/blah.apk => /something
12340            try {
12341                File f = codePath.getCanonicalFile();
12342                File parent = f.getParentFile();    // non-null because codePath is a file
12343                File tmp;
12344                while ((tmp = parent.getParentFile()) != null) {
12345                    f = parent;
12346                    parent = tmp;
12347                }
12348                codeRoot = f;
12349                Slog.w(TAG, "Unrecognized code path "
12350                        + codePath + " - using " + codeRoot);
12351            } catch (IOException e) {
12352                // Can't canonicalize the code path -- shenanigans?
12353                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12354                return Environment.getRootDirectory().getPath();
12355            }
12356        }
12357        return codeRoot.getPath();
12358    }
12359
12360    /**
12361     * Derive and set the location of native libraries for the given package,
12362     * which varies depending on where and how the package was installed.
12363     */
12364    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12365        final ApplicationInfo info = pkg.applicationInfo;
12366        final String codePath = pkg.codePath;
12367        final File codeFile = new File(codePath);
12368        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12369        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12370
12371        info.nativeLibraryRootDir = null;
12372        info.nativeLibraryRootRequiresIsa = false;
12373        info.nativeLibraryDir = null;
12374        info.secondaryNativeLibraryDir = null;
12375
12376        if (isApkFile(codeFile)) {
12377            // Monolithic install
12378            if (bundledApp) {
12379                // If "/system/lib64/apkname" exists, assume that is the per-package
12380                // native library directory to use; otherwise use "/system/lib/apkname".
12381                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12382                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12383                        getPrimaryInstructionSet(info));
12384
12385                // This is a bundled system app so choose the path based on the ABI.
12386                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12387                // is just the default path.
12388                final String apkName = deriveCodePathName(codePath);
12389                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12390                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12391                        apkName).getAbsolutePath();
12392
12393                if (info.secondaryCpuAbi != null) {
12394                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12395                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12396                            secondaryLibDir, apkName).getAbsolutePath();
12397                }
12398            } else if (asecApp) {
12399                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12400                        .getAbsolutePath();
12401            } else {
12402                final String apkName = deriveCodePathName(codePath);
12403                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12404                        .getAbsolutePath();
12405            }
12406
12407            info.nativeLibraryRootRequiresIsa = false;
12408            info.nativeLibraryDir = info.nativeLibraryRootDir;
12409        } else {
12410            // Cluster install
12411            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12412            info.nativeLibraryRootRequiresIsa = true;
12413
12414            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12415                    getPrimaryInstructionSet(info)).getAbsolutePath();
12416
12417            if (info.secondaryCpuAbi != null) {
12418                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12419                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12420            }
12421        }
12422    }
12423
12424    /**
12425     * Calculate the abis and roots for a bundled app. These can uniquely
12426     * be determined from the contents of the system partition, i.e whether
12427     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12428     * of this information, and instead assume that the system was built
12429     * sensibly.
12430     */
12431    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12432                                           PackageSetting pkgSetting) {
12433        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12434
12435        // If "/system/lib64/apkname" exists, assume that is the per-package
12436        // native library directory to use; otherwise use "/system/lib/apkname".
12437        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12438        setBundledAppAbi(pkg, apkRoot, apkName);
12439        // pkgSetting might be null during rescan following uninstall of updates
12440        // to a bundled app, so accommodate that possibility.  The settings in
12441        // that case will be established later from the parsed package.
12442        //
12443        // If the settings aren't null, sync them up with what we've just derived.
12444        // note that apkRoot isn't stored in the package settings.
12445        if (pkgSetting != null) {
12446            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12447            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12448        }
12449    }
12450
12451    /**
12452     * Deduces the ABI of a bundled app and sets the relevant fields on the
12453     * parsed pkg object.
12454     *
12455     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12456     *        under which system libraries are installed.
12457     * @param apkName the name of the installed package.
12458     */
12459    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12460        final File codeFile = new File(pkg.codePath);
12461
12462        final boolean has64BitLibs;
12463        final boolean has32BitLibs;
12464        if (isApkFile(codeFile)) {
12465            // Monolithic install
12466            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12467            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12468        } else {
12469            // Cluster install
12470            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12471            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12472                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12473                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12474                has64BitLibs = (new File(rootDir, isa)).exists();
12475            } else {
12476                has64BitLibs = false;
12477            }
12478            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12479                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12480                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12481                has32BitLibs = (new File(rootDir, isa)).exists();
12482            } else {
12483                has32BitLibs = false;
12484            }
12485        }
12486
12487        if (has64BitLibs && !has32BitLibs) {
12488            // The package has 64 bit libs, but not 32 bit libs. Its primary
12489            // ABI should be 64 bit. We can safely assume here that the bundled
12490            // native libraries correspond to the most preferred ABI in the list.
12491
12492            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12493            pkg.applicationInfo.secondaryCpuAbi = null;
12494        } else if (has32BitLibs && !has64BitLibs) {
12495            // The package has 32 bit libs but not 64 bit libs. Its primary
12496            // ABI should be 32 bit.
12497
12498            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12499            pkg.applicationInfo.secondaryCpuAbi = null;
12500        } else if (has32BitLibs && has64BitLibs) {
12501            // The application has both 64 and 32 bit bundled libraries. We check
12502            // here that the app declares multiArch support, and warn if it doesn't.
12503            //
12504            // We will be lenient here and record both ABIs. The primary will be the
12505            // ABI that's higher on the list, i.e, a device that's configured to prefer
12506            // 64 bit apps will see a 64 bit primary ABI,
12507
12508            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12509                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12510            }
12511
12512            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12513                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12514                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12515            } else {
12516                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12517                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12518            }
12519        } else {
12520            pkg.applicationInfo.primaryCpuAbi = null;
12521            pkg.applicationInfo.secondaryCpuAbi = null;
12522        }
12523    }
12524
12525    private void killApplication(String pkgName, int appId, String reason) {
12526        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12527    }
12528
12529    private void killApplication(String pkgName, int appId, int userId, String reason) {
12530        // Request the ActivityManager to kill the process(only for existing packages)
12531        // so that we do not end up in a confused state while the user is still using the older
12532        // version of the application while the new one gets installed.
12533        final long token = Binder.clearCallingIdentity();
12534        try {
12535            IActivityManager am = ActivityManager.getService();
12536            if (am != null) {
12537                try {
12538                    am.killApplication(pkgName, appId, userId, reason);
12539                } catch (RemoteException e) {
12540                }
12541            }
12542        } finally {
12543            Binder.restoreCallingIdentity(token);
12544        }
12545    }
12546
12547    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12548        // Remove the parent package setting
12549        PackageSetting ps = (PackageSetting) pkg.mExtras;
12550        if (ps != null) {
12551            removePackageLI(ps, chatty);
12552        }
12553        // Remove the child package setting
12554        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12555        for (int i = 0; i < childCount; i++) {
12556            PackageParser.Package childPkg = pkg.childPackages.get(i);
12557            ps = (PackageSetting) childPkg.mExtras;
12558            if (ps != null) {
12559                removePackageLI(ps, chatty);
12560            }
12561        }
12562    }
12563
12564    void removePackageLI(PackageSetting ps, boolean chatty) {
12565        if (DEBUG_INSTALL) {
12566            if (chatty)
12567                Log.d(TAG, "Removing package " + ps.name);
12568        }
12569
12570        // writer
12571        synchronized (mPackages) {
12572            mPackages.remove(ps.name);
12573            final PackageParser.Package pkg = ps.pkg;
12574            if (pkg != null) {
12575                cleanPackageDataStructuresLILPw(pkg, chatty);
12576            }
12577        }
12578    }
12579
12580    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12581        if (DEBUG_INSTALL) {
12582            if (chatty)
12583                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12584        }
12585
12586        // writer
12587        synchronized (mPackages) {
12588            // Remove the parent package
12589            mPackages.remove(pkg.applicationInfo.packageName);
12590            cleanPackageDataStructuresLILPw(pkg, chatty);
12591
12592            // Remove the child packages
12593            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12594            for (int i = 0; i < childCount; i++) {
12595                PackageParser.Package childPkg = pkg.childPackages.get(i);
12596                mPackages.remove(childPkg.applicationInfo.packageName);
12597                cleanPackageDataStructuresLILPw(childPkg, chatty);
12598            }
12599        }
12600    }
12601
12602    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12603        int N = pkg.providers.size();
12604        StringBuilder r = null;
12605        int i;
12606        for (i=0; i<N; i++) {
12607            PackageParser.Provider p = pkg.providers.get(i);
12608            mProviders.removeProvider(p);
12609            if (p.info.authority == null) {
12610
12611                /* There was another ContentProvider with this authority when
12612                 * this app was installed so this authority is null,
12613                 * Ignore it as we don't have to unregister the provider.
12614                 */
12615                continue;
12616            }
12617            String names[] = p.info.authority.split(";");
12618            for (int j = 0; j < names.length; j++) {
12619                if (mProvidersByAuthority.get(names[j]) == p) {
12620                    mProvidersByAuthority.remove(names[j]);
12621                    if (DEBUG_REMOVE) {
12622                        if (chatty)
12623                            Log.d(TAG, "Unregistered content provider: " + names[j]
12624                                    + ", className = " + p.info.name + ", isSyncable = "
12625                                    + p.info.isSyncable);
12626                    }
12627                }
12628            }
12629            if (DEBUG_REMOVE && chatty) {
12630                if (r == null) {
12631                    r = new StringBuilder(256);
12632                } else {
12633                    r.append(' ');
12634                }
12635                r.append(p.info.name);
12636            }
12637        }
12638        if (r != null) {
12639            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12640        }
12641
12642        N = pkg.services.size();
12643        r = null;
12644        for (i=0; i<N; i++) {
12645            PackageParser.Service s = pkg.services.get(i);
12646            mServices.removeService(s);
12647            if (chatty) {
12648                if (r == null) {
12649                    r = new StringBuilder(256);
12650                } else {
12651                    r.append(' ');
12652                }
12653                r.append(s.info.name);
12654            }
12655        }
12656        if (r != null) {
12657            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12658        }
12659
12660        N = pkg.receivers.size();
12661        r = null;
12662        for (i=0; i<N; i++) {
12663            PackageParser.Activity a = pkg.receivers.get(i);
12664            mReceivers.removeActivity(a, "receiver");
12665            if (DEBUG_REMOVE && chatty) {
12666                if (r == null) {
12667                    r = new StringBuilder(256);
12668                } else {
12669                    r.append(' ');
12670                }
12671                r.append(a.info.name);
12672            }
12673        }
12674        if (r != null) {
12675            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12676        }
12677
12678        N = pkg.activities.size();
12679        r = null;
12680        for (i=0; i<N; i++) {
12681            PackageParser.Activity a = pkg.activities.get(i);
12682            mActivities.removeActivity(a, "activity");
12683            if (DEBUG_REMOVE && chatty) {
12684                if (r == null) {
12685                    r = new StringBuilder(256);
12686                } else {
12687                    r.append(' ');
12688                }
12689                r.append(a.info.name);
12690            }
12691        }
12692        if (r != null) {
12693            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12694        }
12695
12696        N = pkg.permissions.size();
12697        r = null;
12698        for (i=0; i<N; i++) {
12699            PackageParser.Permission p = pkg.permissions.get(i);
12700            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12701            if (bp == null) {
12702                bp = mSettings.mPermissionTrees.get(p.info.name);
12703            }
12704            if (bp != null && bp.perm == p) {
12705                bp.perm = null;
12706                if (DEBUG_REMOVE && chatty) {
12707                    if (r == null) {
12708                        r = new StringBuilder(256);
12709                    } else {
12710                        r.append(' ');
12711                    }
12712                    r.append(p.info.name);
12713                }
12714            }
12715            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12716                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12717                if (appOpPkgs != null) {
12718                    appOpPkgs.remove(pkg.packageName);
12719                }
12720            }
12721        }
12722        if (r != null) {
12723            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12724        }
12725
12726        N = pkg.requestedPermissions.size();
12727        r = null;
12728        for (i=0; i<N; i++) {
12729            String perm = pkg.requestedPermissions.get(i);
12730            BasePermission bp = mSettings.mPermissions.get(perm);
12731            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12732                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12733                if (appOpPkgs != null) {
12734                    appOpPkgs.remove(pkg.packageName);
12735                    if (appOpPkgs.isEmpty()) {
12736                        mAppOpPermissionPackages.remove(perm);
12737                    }
12738                }
12739            }
12740        }
12741        if (r != null) {
12742            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12743        }
12744
12745        N = pkg.instrumentation.size();
12746        r = null;
12747        for (i=0; i<N; i++) {
12748            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12749            mInstrumentation.remove(a.getComponentName());
12750            if (DEBUG_REMOVE && chatty) {
12751                if (r == null) {
12752                    r = new StringBuilder(256);
12753                } else {
12754                    r.append(' ');
12755                }
12756                r.append(a.info.name);
12757            }
12758        }
12759        if (r != null) {
12760            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12761        }
12762
12763        r = null;
12764        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12765            // Only system apps can hold shared libraries.
12766            if (pkg.libraryNames != null) {
12767                for (i = 0; i < pkg.libraryNames.size(); i++) {
12768                    String name = pkg.libraryNames.get(i);
12769                    if (removeSharedLibraryLPw(name, 0)) {
12770                        if (DEBUG_REMOVE && chatty) {
12771                            if (r == null) {
12772                                r = new StringBuilder(256);
12773                            } else {
12774                                r.append(' ');
12775                            }
12776                            r.append(name);
12777                        }
12778                    }
12779                }
12780            }
12781        }
12782
12783        r = null;
12784
12785        // Any package can hold static shared libraries.
12786        if (pkg.staticSharedLibName != null) {
12787            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12788                if (DEBUG_REMOVE && chatty) {
12789                    if (r == null) {
12790                        r = new StringBuilder(256);
12791                    } else {
12792                        r.append(' ');
12793                    }
12794                    r.append(pkg.staticSharedLibName);
12795                }
12796            }
12797        }
12798
12799        if (r != null) {
12800            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12801        }
12802    }
12803
12804    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12805        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12806            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12807                return true;
12808            }
12809        }
12810        return false;
12811    }
12812
12813    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12814    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12815    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12816
12817    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12818        // Update the parent permissions
12819        updatePermissionsLPw(pkg.packageName, pkg, flags);
12820        // Update the child permissions
12821        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12822        for (int i = 0; i < childCount; i++) {
12823            PackageParser.Package childPkg = pkg.childPackages.get(i);
12824            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12825        }
12826    }
12827
12828    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12829            int flags) {
12830        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12831        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12832    }
12833
12834    private void updatePermissionsLPw(String changingPkg,
12835            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12836        // Make sure there are no dangling permission trees.
12837        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12838        while (it.hasNext()) {
12839            final BasePermission bp = it.next();
12840            if (bp.packageSetting == null) {
12841                // We may not yet have parsed the package, so just see if
12842                // we still know about its settings.
12843                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12844            }
12845            if (bp.packageSetting == null) {
12846                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12847                        + " from package " + bp.sourcePackage);
12848                it.remove();
12849            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12850                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12851                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12852                            + " from package " + bp.sourcePackage);
12853                    flags |= UPDATE_PERMISSIONS_ALL;
12854                    it.remove();
12855                }
12856            }
12857        }
12858
12859        // Make sure all dynamic permissions have been assigned to a package,
12860        // and make sure there are no dangling permissions.
12861        it = mSettings.mPermissions.values().iterator();
12862        while (it.hasNext()) {
12863            final BasePermission bp = it.next();
12864            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12865                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12866                        + bp.name + " pkg=" + bp.sourcePackage
12867                        + " info=" + bp.pendingInfo);
12868                if (bp.packageSetting == null && bp.pendingInfo != null) {
12869                    final BasePermission tree = findPermissionTreeLP(bp.name);
12870                    if (tree != null && tree.perm != null) {
12871                        bp.packageSetting = tree.packageSetting;
12872                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12873                                new PermissionInfo(bp.pendingInfo));
12874                        bp.perm.info.packageName = tree.perm.info.packageName;
12875                        bp.perm.info.name = bp.name;
12876                        bp.uid = tree.uid;
12877                    }
12878                }
12879            }
12880            if (bp.packageSetting == null) {
12881                // We may not yet have parsed the package, so just see if
12882                // we still know about its settings.
12883                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12884            }
12885            if (bp.packageSetting == null) {
12886                Slog.w(TAG, "Removing dangling permission: " + bp.name
12887                        + " from package " + bp.sourcePackage);
12888                it.remove();
12889            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12890                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12891                    Slog.i(TAG, "Removing old permission: " + bp.name
12892                            + " from package " + bp.sourcePackage);
12893                    flags |= UPDATE_PERMISSIONS_ALL;
12894                    it.remove();
12895                }
12896            }
12897        }
12898
12899        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12900        // Now update the permissions for all packages, in particular
12901        // replace the granted permissions of the system packages.
12902        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12903            for (PackageParser.Package pkg : mPackages.values()) {
12904                if (pkg != pkgInfo) {
12905                    // Only replace for packages on requested volume
12906                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12907                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12908                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12909                    grantPermissionsLPw(pkg, replace, changingPkg);
12910                }
12911            }
12912        }
12913
12914        if (pkgInfo != null) {
12915            // Only replace for packages on requested volume
12916            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12917            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12918                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12919            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12920        }
12921        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12922    }
12923
12924    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12925            String packageOfInterest) {
12926        // IMPORTANT: There are two types of permissions: install and runtime.
12927        // Install time permissions are granted when the app is installed to
12928        // all device users and users added in the future. Runtime permissions
12929        // are granted at runtime explicitly to specific users. Normal and signature
12930        // protected permissions are install time permissions. Dangerous permissions
12931        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12932        // otherwise they are runtime permissions. This function does not manage
12933        // runtime permissions except for the case an app targeting Lollipop MR1
12934        // being upgraded to target a newer SDK, in which case dangerous permissions
12935        // are transformed from install time to runtime ones.
12936
12937        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12938        if (ps == null) {
12939            return;
12940        }
12941
12942        PermissionsState permissionsState = ps.getPermissionsState();
12943        PermissionsState origPermissions = permissionsState;
12944
12945        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12946
12947        boolean runtimePermissionsRevoked = false;
12948        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12949
12950        boolean changedInstallPermission = false;
12951
12952        if (replace) {
12953            ps.installPermissionsFixed = false;
12954            if (!ps.isSharedUser()) {
12955                origPermissions = new PermissionsState(permissionsState);
12956                permissionsState.reset();
12957            } else {
12958                // We need to know only about runtime permission changes since the
12959                // calling code always writes the install permissions state but
12960                // the runtime ones are written only if changed. The only cases of
12961                // changed runtime permissions here are promotion of an install to
12962                // runtime and revocation of a runtime from a shared user.
12963                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12964                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12965                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12966                    runtimePermissionsRevoked = true;
12967                }
12968            }
12969        }
12970
12971        permissionsState.setGlobalGids(mGlobalGids);
12972
12973        final int N = pkg.requestedPermissions.size();
12974        for (int i=0; i<N; i++) {
12975            final String name = pkg.requestedPermissions.get(i);
12976            final BasePermission bp = mSettings.mPermissions.get(name);
12977            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12978                    >= Build.VERSION_CODES.M;
12979
12980            if (DEBUG_INSTALL) {
12981                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12982            }
12983
12984            if (bp == null || bp.packageSetting == null) {
12985                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12986                    if (DEBUG_PERMISSIONS) {
12987                        Slog.i(TAG, "Unknown permission " + name
12988                                + " in package " + pkg.packageName);
12989                    }
12990                }
12991                continue;
12992            }
12993
12994
12995            // Limit ephemeral apps to ephemeral allowed permissions.
12996            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12997                if (DEBUG_PERMISSIONS) {
12998                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12999                            + pkg.packageName);
13000                }
13001                continue;
13002            }
13003
13004            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
13005                if (DEBUG_PERMISSIONS) {
13006                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
13007                            + pkg.packageName);
13008                }
13009                continue;
13010            }
13011
13012            final String perm = bp.name;
13013            boolean allowedSig = false;
13014            int grant = GRANT_DENIED;
13015
13016            // Keep track of app op permissions.
13017            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
13018                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
13019                if (pkgs == null) {
13020                    pkgs = new ArraySet<>();
13021                    mAppOpPermissionPackages.put(bp.name, pkgs);
13022                }
13023                pkgs.add(pkg.packageName);
13024            }
13025
13026            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
13027            switch (level) {
13028                case PermissionInfo.PROTECTION_NORMAL: {
13029                    // For all apps normal permissions are install time ones.
13030                    grant = GRANT_INSTALL;
13031                } break;
13032
13033                case PermissionInfo.PROTECTION_DANGEROUS: {
13034                    // If a permission review is required for legacy apps we represent
13035                    // their permissions as always granted runtime ones since we need
13036                    // to keep the review required permission flag per user while an
13037                    // install permission's state is shared across all users.
13038                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
13039                        // For legacy apps dangerous permissions are install time ones.
13040                        grant = GRANT_INSTALL;
13041                    } else if (origPermissions.hasInstallPermission(bp.name)) {
13042                        // For legacy apps that became modern, install becomes runtime.
13043                        grant = GRANT_UPGRADE;
13044                    } else if (mPromoteSystemApps
13045                            && isSystemApp(ps)
13046                            && mExistingSystemPackages.contains(ps.name)) {
13047                        // For legacy system apps, install becomes runtime.
13048                        // We cannot check hasInstallPermission() for system apps since those
13049                        // permissions were granted implicitly and not persisted pre-M.
13050                        grant = GRANT_UPGRADE;
13051                    } else {
13052                        // For modern apps keep runtime permissions unchanged.
13053                        grant = GRANT_RUNTIME;
13054                    }
13055                } break;
13056
13057                case PermissionInfo.PROTECTION_SIGNATURE: {
13058                    // For all apps signature permissions are install time ones.
13059                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
13060                    if (allowedSig) {
13061                        grant = GRANT_INSTALL;
13062                    }
13063                } break;
13064            }
13065
13066            if (DEBUG_PERMISSIONS) {
13067                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
13068            }
13069
13070            if (grant != GRANT_DENIED) {
13071                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
13072                    // If this is an existing, non-system package, then
13073                    // we can't add any new permissions to it.
13074                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
13075                        // Except...  if this is a permission that was added
13076                        // to the platform (note: need to only do this when
13077                        // updating the platform).
13078                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
13079                            grant = GRANT_DENIED;
13080                        }
13081                    }
13082                }
13083
13084                switch (grant) {
13085                    case GRANT_INSTALL: {
13086                        // Revoke this as runtime permission to handle the case of
13087                        // a runtime permission being downgraded to an install one.
13088                        // Also in permission review mode we keep dangerous permissions
13089                        // for legacy apps
13090                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13091                            if (origPermissions.getRuntimePermissionState(
13092                                    bp.name, userId) != null) {
13093                                // Revoke the runtime permission and clear the flags.
13094                                origPermissions.revokeRuntimePermission(bp, userId);
13095                                origPermissions.updatePermissionFlags(bp, userId,
13096                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
13097                                // If we revoked a permission permission, we have to write.
13098                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13099                                        changedRuntimePermissionUserIds, userId);
13100                            }
13101                        }
13102                        // Grant an install permission.
13103                        if (permissionsState.grantInstallPermission(bp) !=
13104                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13105                            changedInstallPermission = true;
13106                        }
13107                    } break;
13108
13109                    case GRANT_RUNTIME: {
13110                        // Grant previously granted runtime permissions.
13111                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13112                            PermissionState permissionState = origPermissions
13113                                    .getRuntimePermissionState(bp.name, userId);
13114                            int flags = permissionState != null
13115                                    ? permissionState.getFlags() : 0;
13116                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13117                                // Don't propagate the permission in a permission review mode if
13118                                // the former was revoked, i.e. marked to not propagate on upgrade.
13119                                // Note that in a permission review mode install permissions are
13120                                // represented as constantly granted runtime ones since we need to
13121                                // keep a per user state associated with the permission. Also the
13122                                // revoke on upgrade flag is no longer applicable and is reset.
13123                                final boolean revokeOnUpgrade = (flags & PackageManager
13124                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13125                                if (revokeOnUpgrade) {
13126                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13127                                    // Since we changed the flags, we have to write.
13128                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13129                                            changedRuntimePermissionUserIds, userId);
13130                                }
13131                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13132                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13133                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13134                                        // If we cannot put the permission as it was,
13135                                        // we have to write.
13136                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13137                                                changedRuntimePermissionUserIds, userId);
13138                                    }
13139                                }
13140
13141                                // If the app supports runtime permissions no need for a review.
13142                                if (mPermissionReviewRequired
13143                                        && appSupportsRuntimePermissions
13144                                        && (flags & PackageManager
13145                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13146                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13147                                    // Since we changed the flags, we have to write.
13148                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13149                                            changedRuntimePermissionUserIds, userId);
13150                                }
13151                            } else if (mPermissionReviewRequired
13152                                    && !appSupportsRuntimePermissions) {
13153                                // For legacy apps that need a permission review, every new
13154                                // runtime permission is granted but it is pending a review.
13155                                // We also need to review only platform defined runtime
13156                                // permissions as these are the only ones the platform knows
13157                                // how to disable the API to simulate revocation as legacy
13158                                // apps don't expect to run with revoked permissions.
13159                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13160                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13161                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13162                                        // We changed the flags, hence have to write.
13163                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13164                                                changedRuntimePermissionUserIds, userId);
13165                                    }
13166                                }
13167                                if (permissionsState.grantRuntimePermission(bp, userId)
13168                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13169                                    // We changed the permission, hence have to write.
13170                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13171                                            changedRuntimePermissionUserIds, userId);
13172                                }
13173                            }
13174                            // Propagate the permission flags.
13175                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13176                        }
13177                    } break;
13178
13179                    case GRANT_UPGRADE: {
13180                        // Grant runtime permissions for a previously held install permission.
13181                        PermissionState permissionState = origPermissions
13182                                .getInstallPermissionState(bp.name);
13183                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13184
13185                        if (origPermissions.revokeInstallPermission(bp)
13186                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13187                            // We will be transferring the permission flags, so clear them.
13188                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13189                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13190                            changedInstallPermission = true;
13191                        }
13192
13193                        // If the permission is not to be promoted to runtime we ignore it and
13194                        // also its other flags as they are not applicable to install permissions.
13195                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13196                            for (int userId : currentUserIds) {
13197                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13198                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13199                                    // Transfer the permission flags.
13200                                    permissionsState.updatePermissionFlags(bp, userId,
13201                                            flags, flags);
13202                                    // If we granted the permission, we have to write.
13203                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13204                                            changedRuntimePermissionUserIds, userId);
13205                                }
13206                            }
13207                        }
13208                    } break;
13209
13210                    default: {
13211                        if (packageOfInterest == null
13212                                || packageOfInterest.equals(pkg.packageName)) {
13213                            if (DEBUG_PERMISSIONS) {
13214                                Slog.i(TAG, "Not granting permission " + perm
13215                                        + " to package " + pkg.packageName
13216                                        + " because it was previously installed without");
13217                            }
13218                        }
13219                    } break;
13220                }
13221            } else {
13222                if (permissionsState.revokeInstallPermission(bp) !=
13223                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13224                    // Also drop the permission flags.
13225                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13226                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13227                    changedInstallPermission = true;
13228                    Slog.i(TAG, "Un-granting permission " + perm
13229                            + " from package " + pkg.packageName
13230                            + " (protectionLevel=" + bp.protectionLevel
13231                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13232                            + ")");
13233                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13234                    // Don't print warning for app op permissions, since it is fine for them
13235                    // not to be granted, there is a UI for the user to decide.
13236                    if (DEBUG_PERMISSIONS
13237                            && (packageOfInterest == null
13238                                    || packageOfInterest.equals(pkg.packageName))) {
13239                        Slog.i(TAG, "Not granting permission " + perm
13240                                + " to package " + pkg.packageName
13241                                + " (protectionLevel=" + bp.protectionLevel
13242                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13243                                + ")");
13244                    }
13245                }
13246            }
13247        }
13248
13249        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13250                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13251            // This is the first that we have heard about this package, so the
13252            // permissions we have now selected are fixed until explicitly
13253            // changed.
13254            ps.installPermissionsFixed = true;
13255        }
13256
13257        // Persist the runtime permissions state for users with changes. If permissions
13258        // were revoked because no app in the shared user declares them we have to
13259        // write synchronously to avoid losing runtime permissions state.
13260        for (int userId : changedRuntimePermissionUserIds) {
13261            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13262        }
13263    }
13264
13265    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13266        boolean allowed = false;
13267        final int NP = PackageParser.NEW_PERMISSIONS.length;
13268        for (int ip=0; ip<NP; ip++) {
13269            final PackageParser.NewPermissionInfo npi
13270                    = PackageParser.NEW_PERMISSIONS[ip];
13271            if (npi.name.equals(perm)
13272                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13273                allowed = true;
13274                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13275                        + pkg.packageName);
13276                break;
13277            }
13278        }
13279        return allowed;
13280    }
13281
13282    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13283            BasePermission bp, PermissionsState origPermissions) {
13284        boolean privilegedPermission = (bp.protectionLevel
13285                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13286        boolean privappPermissionsDisable =
13287                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13288        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13289        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13290        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13291                && !platformPackage && platformPermission) {
13292            final ArraySet<String> allowedPermissions = SystemConfig.getInstance()
13293                    .getPrivAppPermissions(pkg.packageName);
13294            final boolean whitelisted =
13295                    allowedPermissions != null && allowedPermissions.contains(perm);
13296            if (!whitelisted) {
13297                Slog.w(TAG, "Privileged permission " + perm + " for package "
13298                        + pkg.packageName + " - not in privapp-permissions whitelist");
13299                // Only report violations for apps on system image
13300                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13301                    // it's only a reportable violation if the permission isn't explicitly denied
13302                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13303                            .getPrivAppDenyPermissions(pkg.packageName);
13304                    final boolean permissionViolation =
13305                            deniedPermissions == null || !deniedPermissions.contains(perm);
13306                    if (permissionViolation) {
13307                        if (mPrivappPermissionsViolations == null) {
13308                            mPrivappPermissionsViolations = new ArraySet<>();
13309                        }
13310                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13311                    } else {
13312                        return false;
13313                    }
13314                }
13315                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13316                    return false;
13317                }
13318            }
13319        }
13320        boolean allowed = (compareSignatures(
13321                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13322                        == PackageManager.SIGNATURE_MATCH)
13323                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13324                        == PackageManager.SIGNATURE_MATCH);
13325        if (!allowed && privilegedPermission) {
13326            if (isSystemApp(pkg)) {
13327                // For updated system applications, a system permission
13328                // is granted only if it had been defined by the original application.
13329                if (pkg.isUpdatedSystemApp()) {
13330                    final PackageSetting sysPs = mSettings
13331                            .getDisabledSystemPkgLPr(pkg.packageName);
13332                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13333                        // If the original was granted this permission, we take
13334                        // that grant decision as read and propagate it to the
13335                        // update.
13336                        if (sysPs.isPrivileged()) {
13337                            allowed = true;
13338                        }
13339                    } else {
13340                        // The system apk may have been updated with an older
13341                        // version of the one on the data partition, but which
13342                        // granted a new system permission that it didn't have
13343                        // before.  In this case we do want to allow the app to
13344                        // now get the new permission if the ancestral apk is
13345                        // privileged to get it.
13346                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13347                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13348                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13349                                    allowed = true;
13350                                    break;
13351                                }
13352                            }
13353                        }
13354                        // Also if a privileged parent package on the system image or any of
13355                        // its children requested a privileged permission, the updated child
13356                        // packages can also get the permission.
13357                        if (pkg.parentPackage != null) {
13358                            final PackageSetting disabledSysParentPs = mSettings
13359                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13360                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13361                                    && disabledSysParentPs.isPrivileged()) {
13362                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13363                                    allowed = true;
13364                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13365                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13366                                    for (int i = 0; i < count; i++) {
13367                                        PackageParser.Package disabledSysChildPkg =
13368                                                disabledSysParentPs.pkg.childPackages.get(i);
13369                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13370                                                perm)) {
13371                                            allowed = true;
13372                                            break;
13373                                        }
13374                                    }
13375                                }
13376                            }
13377                        }
13378                    }
13379                } else {
13380                    allowed = isPrivilegedApp(pkg);
13381                }
13382            }
13383        }
13384        if (!allowed) {
13385            if (!allowed && (bp.protectionLevel
13386                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13387                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13388                // If this was a previously normal/dangerous permission that got moved
13389                // to a system permission as part of the runtime permission redesign, then
13390                // we still want to blindly grant it to old apps.
13391                allowed = true;
13392            }
13393            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13394                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13395                // If this permission is to be granted to the system installer and
13396                // this app is an installer, then it gets the permission.
13397                allowed = true;
13398            }
13399            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13400                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13401                // If this permission is to be granted to the system verifier and
13402                // this app is a verifier, then it gets the permission.
13403                allowed = true;
13404            }
13405            if (!allowed && (bp.protectionLevel
13406                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13407                    && isSystemApp(pkg)) {
13408                // Any pre-installed system app is allowed to get this permission.
13409                allowed = true;
13410            }
13411            if (!allowed && (bp.protectionLevel
13412                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13413                // For development permissions, a development permission
13414                // is granted only if it was already granted.
13415                allowed = origPermissions.hasInstallPermission(perm);
13416            }
13417            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13418                    && pkg.packageName.equals(mSetupWizardPackage)) {
13419                // If this permission is to be granted to the system setup wizard and
13420                // this app is a setup wizard, then it gets the permission.
13421                allowed = true;
13422            }
13423        }
13424        return allowed;
13425    }
13426
13427    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13428        final int permCount = pkg.requestedPermissions.size();
13429        for (int j = 0; j < permCount; j++) {
13430            String requestedPermission = pkg.requestedPermissions.get(j);
13431            if (permission.equals(requestedPermission)) {
13432                return true;
13433            }
13434        }
13435        return false;
13436    }
13437
13438    final class ActivityIntentResolver
13439            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13440        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13441                boolean defaultOnly, int userId) {
13442            if (!sUserManager.exists(userId)) return null;
13443            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13444            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13445        }
13446
13447        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13448                int userId) {
13449            if (!sUserManager.exists(userId)) return null;
13450            mFlags = flags;
13451            return super.queryIntent(intent, resolvedType,
13452                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13453                    userId);
13454        }
13455
13456        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13457                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13458            if (!sUserManager.exists(userId)) return null;
13459            if (packageActivities == null) {
13460                return null;
13461            }
13462            mFlags = flags;
13463            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13464            final int N = packageActivities.size();
13465            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13466                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13467
13468            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13469            for (int i = 0; i < N; ++i) {
13470                intentFilters = packageActivities.get(i).intents;
13471                if (intentFilters != null && intentFilters.size() > 0) {
13472                    PackageParser.ActivityIntentInfo[] array =
13473                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13474                    intentFilters.toArray(array);
13475                    listCut.add(array);
13476                }
13477            }
13478            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13479        }
13480
13481        /**
13482         * Finds a privileged activity that matches the specified activity names.
13483         */
13484        private PackageParser.Activity findMatchingActivity(
13485                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13486            for (PackageParser.Activity sysActivity : activityList) {
13487                if (sysActivity.info.name.equals(activityInfo.name)) {
13488                    return sysActivity;
13489                }
13490                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13491                    return sysActivity;
13492                }
13493                if (sysActivity.info.targetActivity != null) {
13494                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13495                        return sysActivity;
13496                    }
13497                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13498                        return sysActivity;
13499                    }
13500                }
13501            }
13502            return null;
13503        }
13504
13505        public class IterGenerator<E> {
13506            public Iterator<E> generate(ActivityIntentInfo info) {
13507                return null;
13508            }
13509        }
13510
13511        public class ActionIterGenerator extends IterGenerator<String> {
13512            @Override
13513            public Iterator<String> generate(ActivityIntentInfo info) {
13514                return info.actionsIterator();
13515            }
13516        }
13517
13518        public class CategoriesIterGenerator extends IterGenerator<String> {
13519            @Override
13520            public Iterator<String> generate(ActivityIntentInfo info) {
13521                return info.categoriesIterator();
13522            }
13523        }
13524
13525        public class SchemesIterGenerator extends IterGenerator<String> {
13526            @Override
13527            public Iterator<String> generate(ActivityIntentInfo info) {
13528                return info.schemesIterator();
13529            }
13530        }
13531
13532        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13533            @Override
13534            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13535                return info.authoritiesIterator();
13536            }
13537        }
13538
13539        /**
13540         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13541         * MODIFIED. Do not pass in a list that should not be changed.
13542         */
13543        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13544                IterGenerator<T> generator, Iterator<T> searchIterator) {
13545            // loop through the set of actions; every one must be found in the intent filter
13546            while (searchIterator.hasNext()) {
13547                // we must have at least one filter in the list to consider a match
13548                if (intentList.size() == 0) {
13549                    break;
13550                }
13551
13552                final T searchAction = searchIterator.next();
13553
13554                // loop through the set of intent filters
13555                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13556                while (intentIter.hasNext()) {
13557                    final ActivityIntentInfo intentInfo = intentIter.next();
13558                    boolean selectionFound = false;
13559
13560                    // loop through the intent filter's selection criteria; at least one
13561                    // of them must match the searched criteria
13562                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13563                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13564                        final T intentSelection = intentSelectionIter.next();
13565                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13566                            selectionFound = true;
13567                            break;
13568                        }
13569                    }
13570
13571                    // the selection criteria wasn't found in this filter's set; this filter
13572                    // is not a potential match
13573                    if (!selectionFound) {
13574                        intentIter.remove();
13575                    }
13576                }
13577            }
13578        }
13579
13580        private boolean isProtectedAction(ActivityIntentInfo filter) {
13581            final Iterator<String> actionsIter = filter.actionsIterator();
13582            while (actionsIter != null && actionsIter.hasNext()) {
13583                final String filterAction = actionsIter.next();
13584                if (PROTECTED_ACTIONS.contains(filterAction)) {
13585                    return true;
13586                }
13587            }
13588            return false;
13589        }
13590
13591        /**
13592         * Adjusts the priority of the given intent filter according to policy.
13593         * <p>
13594         * <ul>
13595         * <li>The priority for non privileged applications is capped to '0'</li>
13596         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13597         * <li>The priority for unbundled updates to privileged applications is capped to the
13598         *      priority defined on the system partition</li>
13599         * </ul>
13600         * <p>
13601         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13602         * allowed to obtain any priority on any action.
13603         */
13604        private void adjustPriority(
13605                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13606            // nothing to do; priority is fine as-is
13607            if (intent.getPriority() <= 0) {
13608                return;
13609            }
13610
13611            final ActivityInfo activityInfo = intent.activity.info;
13612            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13613
13614            final boolean privilegedApp =
13615                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13616            if (!privilegedApp) {
13617                // non-privileged applications can never define a priority >0
13618                if (DEBUG_FILTERS) {
13619                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13620                            + " package: " + applicationInfo.packageName
13621                            + " activity: " + intent.activity.className
13622                            + " origPrio: " + intent.getPriority());
13623                }
13624                intent.setPriority(0);
13625                return;
13626            }
13627
13628            if (systemActivities == null) {
13629                // the system package is not disabled; we're parsing the system partition
13630                if (isProtectedAction(intent)) {
13631                    if (mDeferProtectedFilters) {
13632                        // We can't deal with these just yet. No component should ever obtain a
13633                        // >0 priority for a protected actions, with ONE exception -- the setup
13634                        // wizard. The setup wizard, however, cannot be known until we're able to
13635                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13636                        // until all intent filters have been processed. Chicken, meet egg.
13637                        // Let the filter temporarily have a high priority and rectify the
13638                        // priorities after all system packages have been scanned.
13639                        mProtectedFilters.add(intent);
13640                        if (DEBUG_FILTERS) {
13641                            Slog.i(TAG, "Protected action; save for later;"
13642                                    + " package: " + applicationInfo.packageName
13643                                    + " activity: " + intent.activity.className
13644                                    + " origPrio: " + intent.getPriority());
13645                        }
13646                        return;
13647                    } else {
13648                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13649                            Slog.i(TAG, "No setup wizard;"
13650                                + " All protected intents capped to priority 0");
13651                        }
13652                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13653                            if (DEBUG_FILTERS) {
13654                                Slog.i(TAG, "Found setup wizard;"
13655                                    + " allow priority " + intent.getPriority() + ";"
13656                                    + " package: " + intent.activity.info.packageName
13657                                    + " activity: " + intent.activity.className
13658                                    + " priority: " + intent.getPriority());
13659                            }
13660                            // setup wizard gets whatever it wants
13661                            return;
13662                        }
13663                        if (DEBUG_FILTERS) {
13664                            Slog.i(TAG, "Protected action; cap priority to 0;"
13665                                    + " package: " + intent.activity.info.packageName
13666                                    + " activity: " + intent.activity.className
13667                                    + " origPrio: " + intent.getPriority());
13668                        }
13669                        intent.setPriority(0);
13670                        return;
13671                    }
13672                }
13673                // privileged apps on the system image get whatever priority they request
13674                return;
13675            }
13676
13677            // privileged app unbundled update ... try to find the same activity
13678            final PackageParser.Activity foundActivity =
13679                    findMatchingActivity(systemActivities, activityInfo);
13680            if (foundActivity == null) {
13681                // this is a new activity; it cannot obtain >0 priority
13682                if (DEBUG_FILTERS) {
13683                    Slog.i(TAG, "New activity; cap priority to 0;"
13684                            + " package: " + applicationInfo.packageName
13685                            + " activity: " + intent.activity.className
13686                            + " origPrio: " + intent.getPriority());
13687                }
13688                intent.setPriority(0);
13689                return;
13690            }
13691
13692            // found activity, now check for filter equivalence
13693
13694            // a shallow copy is enough; we modify the list, not its contents
13695            final List<ActivityIntentInfo> intentListCopy =
13696                    new ArrayList<>(foundActivity.intents);
13697            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13698
13699            // find matching action subsets
13700            final Iterator<String> actionsIterator = intent.actionsIterator();
13701            if (actionsIterator != null) {
13702                getIntentListSubset(
13703                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13704                if (intentListCopy.size() == 0) {
13705                    // no more intents to match; we're not equivalent
13706                    if (DEBUG_FILTERS) {
13707                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13708                                + " package: " + applicationInfo.packageName
13709                                + " activity: " + intent.activity.className
13710                                + " origPrio: " + intent.getPriority());
13711                    }
13712                    intent.setPriority(0);
13713                    return;
13714                }
13715            }
13716
13717            // find matching category subsets
13718            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13719            if (categoriesIterator != null) {
13720                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13721                        categoriesIterator);
13722                if (intentListCopy.size() == 0) {
13723                    // no more intents to match; we're not equivalent
13724                    if (DEBUG_FILTERS) {
13725                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13726                                + " package: " + applicationInfo.packageName
13727                                + " activity: " + intent.activity.className
13728                                + " origPrio: " + intent.getPriority());
13729                    }
13730                    intent.setPriority(0);
13731                    return;
13732                }
13733            }
13734
13735            // find matching schemes subsets
13736            final Iterator<String> schemesIterator = intent.schemesIterator();
13737            if (schemesIterator != null) {
13738                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13739                        schemesIterator);
13740                if (intentListCopy.size() == 0) {
13741                    // no more intents to match; we're not equivalent
13742                    if (DEBUG_FILTERS) {
13743                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13744                                + " package: " + applicationInfo.packageName
13745                                + " activity: " + intent.activity.className
13746                                + " origPrio: " + intent.getPriority());
13747                    }
13748                    intent.setPriority(0);
13749                    return;
13750                }
13751            }
13752
13753            // find matching authorities subsets
13754            final Iterator<IntentFilter.AuthorityEntry>
13755                    authoritiesIterator = intent.authoritiesIterator();
13756            if (authoritiesIterator != null) {
13757                getIntentListSubset(intentListCopy,
13758                        new AuthoritiesIterGenerator(),
13759                        authoritiesIterator);
13760                if (intentListCopy.size() == 0) {
13761                    // no more intents to match; we're not equivalent
13762                    if (DEBUG_FILTERS) {
13763                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13764                                + " package: " + applicationInfo.packageName
13765                                + " activity: " + intent.activity.className
13766                                + " origPrio: " + intent.getPriority());
13767                    }
13768                    intent.setPriority(0);
13769                    return;
13770                }
13771            }
13772
13773            // we found matching filter(s); app gets the max priority of all intents
13774            int cappedPriority = 0;
13775            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13776                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13777            }
13778            if (intent.getPriority() > cappedPriority) {
13779                if (DEBUG_FILTERS) {
13780                    Slog.i(TAG, "Found matching filter(s);"
13781                            + " cap priority to " + cappedPriority + ";"
13782                            + " package: " + applicationInfo.packageName
13783                            + " activity: " + intent.activity.className
13784                            + " origPrio: " + intent.getPriority());
13785                }
13786                intent.setPriority(cappedPriority);
13787                return;
13788            }
13789            // all this for nothing; the requested priority was <= what was on the system
13790        }
13791
13792        public final void addActivity(PackageParser.Activity a, String type) {
13793            mActivities.put(a.getComponentName(), a);
13794            if (DEBUG_SHOW_INFO)
13795                Log.v(
13796                TAG, "  " + type + " " +
13797                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13798            if (DEBUG_SHOW_INFO)
13799                Log.v(TAG, "    Class=" + a.info.name);
13800            final int NI = a.intents.size();
13801            for (int j=0; j<NI; j++) {
13802                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13803                if ("activity".equals(type)) {
13804                    final PackageSetting ps =
13805                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13806                    final List<PackageParser.Activity> systemActivities =
13807                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13808                    adjustPriority(systemActivities, intent);
13809                }
13810                if (DEBUG_SHOW_INFO) {
13811                    Log.v(TAG, "    IntentFilter:");
13812                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13813                }
13814                if (!intent.debugCheck()) {
13815                    Log.w(TAG, "==> For Activity " + a.info.name);
13816                }
13817                addFilter(intent);
13818            }
13819        }
13820
13821        public final void removeActivity(PackageParser.Activity a, String type) {
13822            mActivities.remove(a.getComponentName());
13823            if (DEBUG_SHOW_INFO) {
13824                Log.v(TAG, "  " + type + " "
13825                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13826                                : a.info.name) + ":");
13827                Log.v(TAG, "    Class=" + a.info.name);
13828            }
13829            final int NI = a.intents.size();
13830            for (int j=0; j<NI; j++) {
13831                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13832                if (DEBUG_SHOW_INFO) {
13833                    Log.v(TAG, "    IntentFilter:");
13834                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13835                }
13836                removeFilter(intent);
13837            }
13838        }
13839
13840        @Override
13841        protected boolean allowFilterResult(
13842                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13843            ActivityInfo filterAi = filter.activity.info;
13844            for (int i=dest.size()-1; i>=0; i--) {
13845                ActivityInfo destAi = dest.get(i).activityInfo;
13846                if (destAi.name == filterAi.name
13847                        && destAi.packageName == filterAi.packageName) {
13848                    return false;
13849                }
13850            }
13851            return true;
13852        }
13853
13854        @Override
13855        protected ActivityIntentInfo[] newArray(int size) {
13856            return new ActivityIntentInfo[size];
13857        }
13858
13859        @Override
13860        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13861            if (!sUserManager.exists(userId)) return true;
13862            PackageParser.Package p = filter.activity.owner;
13863            if (p != null) {
13864                PackageSetting ps = (PackageSetting)p.mExtras;
13865                if (ps != null) {
13866                    // System apps are never considered stopped for purposes of
13867                    // filtering, because there may be no way for the user to
13868                    // actually re-launch them.
13869                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13870                            && ps.getStopped(userId);
13871                }
13872            }
13873            return false;
13874        }
13875
13876        @Override
13877        protected boolean isPackageForFilter(String packageName,
13878                PackageParser.ActivityIntentInfo info) {
13879            return packageName.equals(info.activity.owner.packageName);
13880        }
13881
13882        @Override
13883        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13884                int match, int userId) {
13885            if (!sUserManager.exists(userId)) return null;
13886            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13887                return null;
13888            }
13889            final PackageParser.Activity activity = info.activity;
13890            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13891            if (ps == null) {
13892                return null;
13893            }
13894            final PackageUserState userState = ps.readUserState(userId);
13895            ActivityInfo ai =
13896                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13897            if (ai == null) {
13898                return null;
13899            }
13900            final boolean matchExplicitlyVisibleOnly =
13901                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13902            final boolean matchVisibleToInstantApp =
13903                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13904            final boolean componentVisible =
13905                    matchVisibleToInstantApp
13906                    && info.isVisibleToInstantApp()
13907                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13908            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13909            // throw out filters that aren't visible to ephemeral apps
13910            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13911                return null;
13912            }
13913            // throw out instant app filters if we're not explicitly requesting them
13914            if (!matchInstantApp && userState.instantApp) {
13915                return null;
13916            }
13917            // throw out instant app filters if updates are available; will trigger
13918            // instant app resolution
13919            if (userState.instantApp && ps.isUpdateAvailable()) {
13920                return null;
13921            }
13922            final ResolveInfo res = new ResolveInfo();
13923            res.activityInfo = ai;
13924            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13925                res.filter = info;
13926            }
13927            if (info != null) {
13928                res.handleAllWebDataURI = info.handleAllWebDataURI();
13929            }
13930            res.priority = info.getPriority();
13931            res.preferredOrder = activity.owner.mPreferredOrder;
13932            //System.out.println("Result: " + res.activityInfo.className +
13933            //                   " = " + res.priority);
13934            res.match = match;
13935            res.isDefault = info.hasDefault;
13936            res.labelRes = info.labelRes;
13937            res.nonLocalizedLabel = info.nonLocalizedLabel;
13938            if (userNeedsBadging(userId)) {
13939                res.noResourceId = true;
13940            } else {
13941                res.icon = info.icon;
13942            }
13943            res.iconResourceId = info.icon;
13944            res.system = res.activityInfo.applicationInfo.isSystemApp();
13945            res.isInstantAppAvailable = userState.instantApp;
13946            return res;
13947        }
13948
13949        @Override
13950        protected void sortResults(List<ResolveInfo> results) {
13951            Collections.sort(results, mResolvePrioritySorter);
13952        }
13953
13954        @Override
13955        protected void dumpFilter(PrintWriter out, String prefix,
13956                PackageParser.ActivityIntentInfo filter) {
13957            out.print(prefix); out.print(
13958                    Integer.toHexString(System.identityHashCode(filter.activity)));
13959                    out.print(' ');
13960                    filter.activity.printComponentShortName(out);
13961                    out.print(" filter ");
13962                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13963        }
13964
13965        @Override
13966        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13967            return filter.activity;
13968        }
13969
13970        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13971            PackageParser.Activity activity = (PackageParser.Activity)label;
13972            out.print(prefix); out.print(
13973                    Integer.toHexString(System.identityHashCode(activity)));
13974                    out.print(' ');
13975                    activity.printComponentShortName(out);
13976            if (count > 1) {
13977                out.print(" ("); out.print(count); out.print(" filters)");
13978            }
13979            out.println();
13980        }
13981
13982        // Keys are String (activity class name), values are Activity.
13983        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13984                = new ArrayMap<ComponentName, PackageParser.Activity>();
13985        private int mFlags;
13986    }
13987
13988    private final class ServiceIntentResolver
13989            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13990        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13991                boolean defaultOnly, int userId) {
13992            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13993            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13994        }
13995
13996        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13997                int userId) {
13998            if (!sUserManager.exists(userId)) return null;
13999            mFlags = flags;
14000            return super.queryIntent(intent, resolvedType,
14001                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14002                    userId);
14003        }
14004
14005        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14006                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
14007            if (!sUserManager.exists(userId)) return null;
14008            if (packageServices == null) {
14009                return null;
14010            }
14011            mFlags = flags;
14012            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
14013            final int N = packageServices.size();
14014            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
14015                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
14016
14017            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
14018            for (int i = 0; i < N; ++i) {
14019                intentFilters = packageServices.get(i).intents;
14020                if (intentFilters != null && intentFilters.size() > 0) {
14021                    PackageParser.ServiceIntentInfo[] array =
14022                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
14023                    intentFilters.toArray(array);
14024                    listCut.add(array);
14025                }
14026            }
14027            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14028        }
14029
14030        public final void addService(PackageParser.Service s) {
14031            mServices.put(s.getComponentName(), s);
14032            if (DEBUG_SHOW_INFO) {
14033                Log.v(TAG, "  "
14034                        + (s.info.nonLocalizedLabel != null
14035                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14036                Log.v(TAG, "    Class=" + s.info.name);
14037            }
14038            final int NI = s.intents.size();
14039            int j;
14040            for (j=0; j<NI; j++) {
14041                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14042                if (DEBUG_SHOW_INFO) {
14043                    Log.v(TAG, "    IntentFilter:");
14044                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14045                }
14046                if (!intent.debugCheck()) {
14047                    Log.w(TAG, "==> For Service " + s.info.name);
14048                }
14049                addFilter(intent);
14050            }
14051        }
14052
14053        public final void removeService(PackageParser.Service s) {
14054            mServices.remove(s.getComponentName());
14055            if (DEBUG_SHOW_INFO) {
14056                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
14057                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14058                Log.v(TAG, "    Class=" + s.info.name);
14059            }
14060            final int NI = s.intents.size();
14061            int j;
14062            for (j=0; j<NI; j++) {
14063                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14064                if (DEBUG_SHOW_INFO) {
14065                    Log.v(TAG, "    IntentFilter:");
14066                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14067                }
14068                removeFilter(intent);
14069            }
14070        }
14071
14072        @Override
14073        protected boolean allowFilterResult(
14074                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
14075            ServiceInfo filterSi = filter.service.info;
14076            for (int i=dest.size()-1; i>=0; i--) {
14077                ServiceInfo destAi = dest.get(i).serviceInfo;
14078                if (destAi.name == filterSi.name
14079                        && destAi.packageName == filterSi.packageName) {
14080                    return false;
14081                }
14082            }
14083            return true;
14084        }
14085
14086        @Override
14087        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
14088            return new PackageParser.ServiceIntentInfo[size];
14089        }
14090
14091        @Override
14092        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
14093            if (!sUserManager.exists(userId)) return true;
14094            PackageParser.Package p = filter.service.owner;
14095            if (p != null) {
14096                PackageSetting ps = (PackageSetting)p.mExtras;
14097                if (ps != null) {
14098                    // System apps are never considered stopped for purposes of
14099                    // filtering, because there may be no way for the user to
14100                    // actually re-launch them.
14101                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14102                            && ps.getStopped(userId);
14103                }
14104            }
14105            return false;
14106        }
14107
14108        @Override
14109        protected boolean isPackageForFilter(String packageName,
14110                PackageParser.ServiceIntentInfo info) {
14111            return packageName.equals(info.service.owner.packageName);
14112        }
14113
14114        @Override
14115        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14116                int match, int userId) {
14117            if (!sUserManager.exists(userId)) return null;
14118            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14119            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14120                return null;
14121            }
14122            final PackageParser.Service service = info.service;
14123            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14124            if (ps == null) {
14125                return null;
14126            }
14127            final PackageUserState userState = ps.readUserState(userId);
14128            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14129                    userState, userId);
14130            if (si == null) {
14131                return null;
14132            }
14133            final boolean matchVisibleToInstantApp =
14134                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14135            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14136            // throw out filters that aren't visible to ephemeral apps
14137            if (matchVisibleToInstantApp
14138                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14139                return null;
14140            }
14141            // throw out ephemeral filters if we're not explicitly requesting them
14142            if (!isInstantApp && userState.instantApp) {
14143                return null;
14144            }
14145            // throw out instant app filters if updates are available; will trigger
14146            // instant app resolution
14147            if (userState.instantApp && ps.isUpdateAvailable()) {
14148                return null;
14149            }
14150            final ResolveInfo res = new ResolveInfo();
14151            res.serviceInfo = si;
14152            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14153                res.filter = filter;
14154            }
14155            res.priority = info.getPriority();
14156            res.preferredOrder = service.owner.mPreferredOrder;
14157            res.match = match;
14158            res.isDefault = info.hasDefault;
14159            res.labelRes = info.labelRes;
14160            res.nonLocalizedLabel = info.nonLocalizedLabel;
14161            res.icon = info.icon;
14162            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14163            return res;
14164        }
14165
14166        @Override
14167        protected void sortResults(List<ResolveInfo> results) {
14168            Collections.sort(results, mResolvePrioritySorter);
14169        }
14170
14171        @Override
14172        protected void dumpFilter(PrintWriter out, String prefix,
14173                PackageParser.ServiceIntentInfo filter) {
14174            out.print(prefix); out.print(
14175                    Integer.toHexString(System.identityHashCode(filter.service)));
14176                    out.print(' ');
14177                    filter.service.printComponentShortName(out);
14178                    out.print(" filter ");
14179                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14180        }
14181
14182        @Override
14183        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14184            return filter.service;
14185        }
14186
14187        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14188            PackageParser.Service service = (PackageParser.Service)label;
14189            out.print(prefix); out.print(
14190                    Integer.toHexString(System.identityHashCode(service)));
14191                    out.print(' ');
14192                    service.printComponentShortName(out);
14193            if (count > 1) {
14194                out.print(" ("); out.print(count); out.print(" filters)");
14195            }
14196            out.println();
14197        }
14198
14199//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14200//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14201//            final List<ResolveInfo> retList = Lists.newArrayList();
14202//            while (i.hasNext()) {
14203//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14204//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14205//                    retList.add(resolveInfo);
14206//                }
14207//            }
14208//            return retList;
14209//        }
14210
14211        // Keys are String (activity class name), values are Activity.
14212        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14213                = new ArrayMap<ComponentName, PackageParser.Service>();
14214        private int mFlags;
14215    }
14216
14217    private final class ProviderIntentResolver
14218            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14219        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14220                boolean defaultOnly, int userId) {
14221            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14222            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14223        }
14224
14225        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14226                int userId) {
14227            if (!sUserManager.exists(userId))
14228                return null;
14229            mFlags = flags;
14230            return super.queryIntent(intent, resolvedType,
14231                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14232                    userId);
14233        }
14234
14235        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14236                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14237            if (!sUserManager.exists(userId))
14238                return null;
14239            if (packageProviders == null) {
14240                return null;
14241            }
14242            mFlags = flags;
14243            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14244            final int N = packageProviders.size();
14245            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14246                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14247
14248            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14249            for (int i = 0; i < N; ++i) {
14250                intentFilters = packageProviders.get(i).intents;
14251                if (intentFilters != null && intentFilters.size() > 0) {
14252                    PackageParser.ProviderIntentInfo[] array =
14253                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14254                    intentFilters.toArray(array);
14255                    listCut.add(array);
14256                }
14257            }
14258            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14259        }
14260
14261        public final void addProvider(PackageParser.Provider p) {
14262            if (mProviders.containsKey(p.getComponentName())) {
14263                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14264                return;
14265            }
14266
14267            mProviders.put(p.getComponentName(), p);
14268            if (DEBUG_SHOW_INFO) {
14269                Log.v(TAG, "  "
14270                        + (p.info.nonLocalizedLabel != null
14271                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14272                Log.v(TAG, "    Class=" + p.info.name);
14273            }
14274            final int NI = p.intents.size();
14275            int j;
14276            for (j = 0; j < NI; j++) {
14277                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14278                if (DEBUG_SHOW_INFO) {
14279                    Log.v(TAG, "    IntentFilter:");
14280                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14281                }
14282                if (!intent.debugCheck()) {
14283                    Log.w(TAG, "==> For Provider " + p.info.name);
14284                }
14285                addFilter(intent);
14286            }
14287        }
14288
14289        public final void removeProvider(PackageParser.Provider p) {
14290            mProviders.remove(p.getComponentName());
14291            if (DEBUG_SHOW_INFO) {
14292                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14293                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14294                Log.v(TAG, "    Class=" + p.info.name);
14295            }
14296            final int NI = p.intents.size();
14297            int j;
14298            for (j = 0; j < NI; j++) {
14299                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14300                if (DEBUG_SHOW_INFO) {
14301                    Log.v(TAG, "    IntentFilter:");
14302                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14303                }
14304                removeFilter(intent);
14305            }
14306        }
14307
14308        @Override
14309        protected boolean allowFilterResult(
14310                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14311            ProviderInfo filterPi = filter.provider.info;
14312            for (int i = dest.size() - 1; i >= 0; i--) {
14313                ProviderInfo destPi = dest.get(i).providerInfo;
14314                if (destPi.name == filterPi.name
14315                        && destPi.packageName == filterPi.packageName) {
14316                    return false;
14317                }
14318            }
14319            return true;
14320        }
14321
14322        @Override
14323        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14324            return new PackageParser.ProviderIntentInfo[size];
14325        }
14326
14327        @Override
14328        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14329            if (!sUserManager.exists(userId))
14330                return true;
14331            PackageParser.Package p = filter.provider.owner;
14332            if (p != null) {
14333                PackageSetting ps = (PackageSetting) p.mExtras;
14334                if (ps != null) {
14335                    // System apps are never considered stopped for purposes of
14336                    // filtering, because there may be no way for the user to
14337                    // actually re-launch them.
14338                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14339                            && ps.getStopped(userId);
14340                }
14341            }
14342            return false;
14343        }
14344
14345        @Override
14346        protected boolean isPackageForFilter(String packageName,
14347                PackageParser.ProviderIntentInfo info) {
14348            return packageName.equals(info.provider.owner.packageName);
14349        }
14350
14351        @Override
14352        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14353                int match, int userId) {
14354            if (!sUserManager.exists(userId))
14355                return null;
14356            final PackageParser.ProviderIntentInfo info = filter;
14357            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14358                return null;
14359            }
14360            final PackageParser.Provider provider = info.provider;
14361            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14362            if (ps == null) {
14363                return null;
14364            }
14365            final PackageUserState userState = ps.readUserState(userId);
14366            final boolean matchVisibleToInstantApp =
14367                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14368            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14369            // throw out filters that aren't visible to instant applications
14370            if (matchVisibleToInstantApp
14371                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14372                return null;
14373            }
14374            // throw out instant application filters if we're not explicitly requesting them
14375            if (!isInstantApp && userState.instantApp) {
14376                return null;
14377            }
14378            // throw out instant application filters if updates are available; will trigger
14379            // instant application resolution
14380            if (userState.instantApp && ps.isUpdateAvailable()) {
14381                return null;
14382            }
14383            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14384                    userState, userId);
14385            if (pi == null) {
14386                return null;
14387            }
14388            final ResolveInfo res = new ResolveInfo();
14389            res.providerInfo = pi;
14390            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14391                res.filter = filter;
14392            }
14393            res.priority = info.getPriority();
14394            res.preferredOrder = provider.owner.mPreferredOrder;
14395            res.match = match;
14396            res.isDefault = info.hasDefault;
14397            res.labelRes = info.labelRes;
14398            res.nonLocalizedLabel = info.nonLocalizedLabel;
14399            res.icon = info.icon;
14400            res.system = res.providerInfo.applicationInfo.isSystemApp();
14401            return res;
14402        }
14403
14404        @Override
14405        protected void sortResults(List<ResolveInfo> results) {
14406            Collections.sort(results, mResolvePrioritySorter);
14407        }
14408
14409        @Override
14410        protected void dumpFilter(PrintWriter out, String prefix,
14411                PackageParser.ProviderIntentInfo filter) {
14412            out.print(prefix);
14413            out.print(
14414                    Integer.toHexString(System.identityHashCode(filter.provider)));
14415            out.print(' ');
14416            filter.provider.printComponentShortName(out);
14417            out.print(" filter ");
14418            out.println(Integer.toHexString(System.identityHashCode(filter)));
14419        }
14420
14421        @Override
14422        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14423            return filter.provider;
14424        }
14425
14426        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14427            PackageParser.Provider provider = (PackageParser.Provider)label;
14428            out.print(prefix); out.print(
14429                    Integer.toHexString(System.identityHashCode(provider)));
14430                    out.print(' ');
14431                    provider.printComponentShortName(out);
14432            if (count > 1) {
14433                out.print(" ("); out.print(count); out.print(" filters)");
14434            }
14435            out.println();
14436        }
14437
14438        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14439                = new ArrayMap<ComponentName, PackageParser.Provider>();
14440        private int mFlags;
14441    }
14442
14443    static final class EphemeralIntentResolver
14444            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14445        /**
14446         * The result that has the highest defined order. Ordering applies on a
14447         * per-package basis. Mapping is from package name to Pair of order and
14448         * EphemeralResolveInfo.
14449         * <p>
14450         * NOTE: This is implemented as a field variable for convenience and efficiency.
14451         * By having a field variable, we're able to track filter ordering as soon as
14452         * a non-zero order is defined. Otherwise, multiple loops across the result set
14453         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14454         * this needs to be contained entirely within {@link #filterResults}.
14455         */
14456        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14457
14458        @Override
14459        protected AuxiliaryResolveInfo[] newArray(int size) {
14460            return new AuxiliaryResolveInfo[size];
14461        }
14462
14463        @Override
14464        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14465            return true;
14466        }
14467
14468        @Override
14469        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14470                int userId) {
14471            if (!sUserManager.exists(userId)) {
14472                return null;
14473            }
14474            final String packageName = responseObj.resolveInfo.getPackageName();
14475            final Integer order = responseObj.getOrder();
14476            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14477                    mOrderResult.get(packageName);
14478            // ordering is enabled and this item's order isn't high enough
14479            if (lastOrderResult != null && lastOrderResult.first >= order) {
14480                return null;
14481            }
14482            final InstantAppResolveInfo res = responseObj.resolveInfo;
14483            if (order > 0) {
14484                // non-zero order, enable ordering
14485                mOrderResult.put(packageName, new Pair<>(order, res));
14486            }
14487            return responseObj;
14488        }
14489
14490        @Override
14491        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14492            // only do work if ordering is enabled [most of the time it won't be]
14493            if (mOrderResult.size() == 0) {
14494                return;
14495            }
14496            int resultSize = results.size();
14497            for (int i = 0; i < resultSize; i++) {
14498                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14499                final String packageName = info.getPackageName();
14500                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14501                if (savedInfo == null) {
14502                    // package doesn't having ordering
14503                    continue;
14504                }
14505                if (savedInfo.second == info) {
14506                    // circled back to the highest ordered item; remove from order list
14507                    mOrderResult.remove(packageName);
14508                    if (mOrderResult.size() == 0) {
14509                        // no more ordered items
14510                        break;
14511                    }
14512                    continue;
14513                }
14514                // item has a worse order, remove it from the result list
14515                results.remove(i);
14516                resultSize--;
14517                i--;
14518            }
14519        }
14520    }
14521
14522    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14523            new Comparator<ResolveInfo>() {
14524        public int compare(ResolveInfo r1, ResolveInfo r2) {
14525            int v1 = r1.priority;
14526            int v2 = r2.priority;
14527            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14528            if (v1 != v2) {
14529                return (v1 > v2) ? -1 : 1;
14530            }
14531            v1 = r1.preferredOrder;
14532            v2 = r2.preferredOrder;
14533            if (v1 != v2) {
14534                return (v1 > v2) ? -1 : 1;
14535            }
14536            if (r1.isDefault != r2.isDefault) {
14537                return r1.isDefault ? -1 : 1;
14538            }
14539            v1 = r1.match;
14540            v2 = r2.match;
14541            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14542            if (v1 != v2) {
14543                return (v1 > v2) ? -1 : 1;
14544            }
14545            if (r1.system != r2.system) {
14546                return r1.system ? -1 : 1;
14547            }
14548            if (r1.activityInfo != null) {
14549                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14550            }
14551            if (r1.serviceInfo != null) {
14552                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14553            }
14554            if (r1.providerInfo != null) {
14555                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14556            }
14557            return 0;
14558        }
14559    };
14560
14561    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14562            new Comparator<ProviderInfo>() {
14563        public int compare(ProviderInfo p1, ProviderInfo p2) {
14564            final int v1 = p1.initOrder;
14565            final int v2 = p2.initOrder;
14566            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14567        }
14568    };
14569
14570    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14571            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14572            final int[] userIds) {
14573        mHandler.post(new Runnable() {
14574            @Override
14575            public void run() {
14576                try {
14577                    final IActivityManager am = ActivityManager.getService();
14578                    if (am == null) return;
14579                    final int[] resolvedUserIds;
14580                    if (userIds == null) {
14581                        resolvedUserIds = am.getRunningUserIds();
14582                    } else {
14583                        resolvedUserIds = userIds;
14584                    }
14585                    for (int id : resolvedUserIds) {
14586                        final Intent intent = new Intent(action,
14587                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14588                        if (extras != null) {
14589                            intent.putExtras(extras);
14590                        }
14591                        if (targetPkg != null) {
14592                            intent.setPackage(targetPkg);
14593                        }
14594                        // Modify the UID when posting to other users
14595                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14596                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14597                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14598                            intent.putExtra(Intent.EXTRA_UID, uid);
14599                        }
14600                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14601                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14602                        if (DEBUG_BROADCASTS) {
14603                            RuntimeException here = new RuntimeException("here");
14604                            here.fillInStackTrace();
14605                            Slog.d(TAG, "Sending to user " + id + ": "
14606                                    + intent.toShortString(false, true, false, false)
14607                                    + " " + intent.getExtras(), here);
14608                        }
14609                        am.broadcastIntent(null, intent, null, finishedReceiver,
14610                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14611                                null, finishedReceiver != null, false, id);
14612                    }
14613                } catch (RemoteException ex) {
14614                }
14615            }
14616        });
14617    }
14618
14619    /**
14620     * Check if the external storage media is available. This is true if there
14621     * is a mounted external storage medium or if the external storage is
14622     * emulated.
14623     */
14624    private boolean isExternalMediaAvailable() {
14625        return mMediaMounted || Environment.isExternalStorageEmulated();
14626    }
14627
14628    @Override
14629    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14630        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14631            return null;
14632        }
14633        if (!isExternalMediaAvailable()) {
14634                // If the external storage is no longer mounted at this point,
14635                // the caller may not have been able to delete all of this
14636                // packages files and can not delete any more.  Bail.
14637            return null;
14638        }
14639        synchronized (mPackages) {
14640            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14641            if (lastPackage != null) {
14642                pkgs.remove(lastPackage);
14643            }
14644            if (pkgs.size() > 0) {
14645                return pkgs.get(0);
14646            }
14647        }
14648        return null;
14649    }
14650
14651    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14652        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14653                userId, andCode ? 1 : 0, packageName);
14654        if (mSystemReady) {
14655            msg.sendToTarget();
14656        } else {
14657            if (mPostSystemReadyMessages == null) {
14658                mPostSystemReadyMessages = new ArrayList<>();
14659            }
14660            mPostSystemReadyMessages.add(msg);
14661        }
14662    }
14663
14664    void startCleaningPackages() {
14665        // reader
14666        if (!isExternalMediaAvailable()) {
14667            return;
14668        }
14669        synchronized (mPackages) {
14670            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14671                return;
14672            }
14673        }
14674        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14675        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14676        IActivityManager am = ActivityManager.getService();
14677        if (am != null) {
14678            int dcsUid = -1;
14679            synchronized (mPackages) {
14680                if (!mDefaultContainerWhitelisted) {
14681                    mDefaultContainerWhitelisted = true;
14682                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14683                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14684                }
14685            }
14686            try {
14687                if (dcsUid > 0) {
14688                    am.backgroundWhitelistUid(dcsUid);
14689                }
14690                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14691                        UserHandle.USER_SYSTEM);
14692            } catch (RemoteException e) {
14693            }
14694        }
14695    }
14696
14697    @Override
14698    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14699            int installFlags, String installerPackageName, int userId) {
14700        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14701
14702        final int callingUid = Binder.getCallingUid();
14703        enforceCrossUserPermission(callingUid, userId,
14704                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14705
14706        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14707            try {
14708                if (observer != null) {
14709                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14710                }
14711            } catch (RemoteException re) {
14712            }
14713            return;
14714        }
14715
14716        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14717            installFlags |= PackageManager.INSTALL_FROM_ADB;
14718
14719        } else {
14720            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14721            // about installerPackageName.
14722
14723            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14724            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14725        }
14726
14727        UserHandle user;
14728        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14729            user = UserHandle.ALL;
14730        } else {
14731            user = new UserHandle(userId);
14732        }
14733
14734        // Only system components can circumvent runtime permissions when installing.
14735        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14736                && mContext.checkCallingOrSelfPermission(Manifest.permission
14737                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14738            throw new SecurityException("You need the "
14739                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14740                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14741        }
14742
14743        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14744                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14745            throw new IllegalArgumentException(
14746                    "New installs into ASEC containers no longer supported");
14747        }
14748
14749        final File originFile = new File(originPath);
14750        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14751
14752        final Message msg = mHandler.obtainMessage(INIT_COPY);
14753        final VerificationInfo verificationInfo = new VerificationInfo(
14754                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14755        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14756                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14757                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14758                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14759        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14760        msg.obj = params;
14761
14762        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14763                System.identityHashCode(msg.obj));
14764        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14765                System.identityHashCode(msg.obj));
14766
14767        mHandler.sendMessage(msg);
14768    }
14769
14770
14771    /**
14772     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14773     * it is acting on behalf on an enterprise or the user).
14774     *
14775     * Note that the ordering of the conditionals in this method is important. The checks we perform
14776     * are as follows, in this order:
14777     *
14778     * 1) If the install is being performed by a system app, we can trust the app to have set the
14779     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14780     *    what it is.
14781     * 2) If the install is being performed by a device or profile owner app, the install reason
14782     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14783     *    set the install reason correctly. If the app targets an older SDK version where install
14784     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14785     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14786     * 3) In all other cases, the install is being performed by a regular app that is neither part
14787     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14788     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14789     *    set to enterprise policy and if so, change it to unknown instead.
14790     */
14791    private int fixUpInstallReason(String installerPackageName, int installerUid,
14792            int installReason) {
14793        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14794                == PERMISSION_GRANTED) {
14795            // If the install is being performed by a system app, we trust that app to have set the
14796            // install reason correctly.
14797            return installReason;
14798        }
14799
14800        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14801            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14802        if (dpm != null) {
14803            ComponentName owner = null;
14804            try {
14805                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14806                if (owner == null) {
14807                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14808                }
14809            } catch (RemoteException e) {
14810            }
14811            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14812                // If the install is being performed by a device or profile owner, the install
14813                // reason should be enterprise policy.
14814                return PackageManager.INSTALL_REASON_POLICY;
14815            }
14816        }
14817
14818        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14819            // If the install is being performed by a regular app (i.e. neither system app nor
14820            // device or profile owner), we have no reason to believe that the app is acting on
14821            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14822            // change it to unknown instead.
14823            return PackageManager.INSTALL_REASON_UNKNOWN;
14824        }
14825
14826        // If the install is being performed by a regular app and the install reason was set to any
14827        // value but enterprise policy, leave the install reason unchanged.
14828        return installReason;
14829    }
14830
14831    void installStage(String packageName, File stagedDir, String stagedCid,
14832            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14833            String installerPackageName, int installerUid, UserHandle user,
14834            Certificate[][] certificates) {
14835        if (DEBUG_EPHEMERAL) {
14836            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14837                Slog.d(TAG, "Ephemeral install of " + packageName);
14838            }
14839        }
14840        final VerificationInfo verificationInfo = new VerificationInfo(
14841                sessionParams.originatingUri, sessionParams.referrerUri,
14842                sessionParams.originatingUid, installerUid);
14843
14844        final OriginInfo origin;
14845        if (stagedDir != null) {
14846            origin = OriginInfo.fromStagedFile(stagedDir);
14847        } else {
14848            origin = OriginInfo.fromStagedContainer(stagedCid);
14849        }
14850
14851        final Message msg = mHandler.obtainMessage(INIT_COPY);
14852        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14853                sessionParams.installReason);
14854        final InstallParams params = new InstallParams(origin, null, observer,
14855                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14856                verificationInfo, user, sessionParams.abiOverride,
14857                sessionParams.grantedRuntimePermissions, certificates, installReason);
14858        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14859        msg.obj = params;
14860
14861        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14862                System.identityHashCode(msg.obj));
14863        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14864                System.identityHashCode(msg.obj));
14865
14866        mHandler.sendMessage(msg);
14867    }
14868
14869    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14870            int userId) {
14871        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14872        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14873                false /*startReceiver*/, pkgSetting.appId, userId);
14874
14875        // Send a session commit broadcast
14876        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14877        info.installReason = pkgSetting.getInstallReason(userId);
14878        info.appPackageName = packageName;
14879        sendSessionCommitBroadcast(info, userId);
14880    }
14881
14882    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14883            boolean includeStopped, int appId, int... userIds) {
14884        if (ArrayUtils.isEmpty(userIds)) {
14885            return;
14886        }
14887        Bundle extras = new Bundle(1);
14888        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14889        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14890
14891        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14892                packageName, extras, 0, null, null, userIds);
14893        if (sendBootCompleted) {
14894            mHandler.post(() -> {
14895                        for (int userId : userIds) {
14896                            sendBootCompletedBroadcastToSystemApp(
14897                                    packageName, includeStopped, userId);
14898                        }
14899                    }
14900            );
14901        }
14902    }
14903
14904    /**
14905     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14906     * automatically without needing an explicit launch.
14907     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14908     */
14909    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14910            int userId) {
14911        // If user is not running, the app didn't miss any broadcast
14912        if (!mUserManagerInternal.isUserRunning(userId)) {
14913            return;
14914        }
14915        final IActivityManager am = ActivityManager.getService();
14916        try {
14917            // Deliver LOCKED_BOOT_COMPLETED first
14918            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14919                    .setPackage(packageName);
14920            if (includeStopped) {
14921                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14922            }
14923            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14924            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14925                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14926
14927            // Deliver BOOT_COMPLETED only if user is unlocked
14928            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14929                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14930                if (includeStopped) {
14931                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14932                }
14933                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14934                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14935            }
14936        } catch (RemoteException e) {
14937            throw e.rethrowFromSystemServer();
14938        }
14939    }
14940
14941    @Override
14942    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14943            int userId) {
14944        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14945        PackageSetting pkgSetting;
14946        final int callingUid = Binder.getCallingUid();
14947        enforceCrossUserPermission(callingUid, userId,
14948                true /* requireFullPermission */, true /* checkShell */,
14949                "setApplicationHiddenSetting for user " + userId);
14950
14951        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14952            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14953            return false;
14954        }
14955
14956        long callingId = Binder.clearCallingIdentity();
14957        try {
14958            boolean sendAdded = false;
14959            boolean sendRemoved = false;
14960            // writer
14961            synchronized (mPackages) {
14962                pkgSetting = mSettings.mPackages.get(packageName);
14963                if (pkgSetting == null) {
14964                    return false;
14965                }
14966                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14967                    return false;
14968                }
14969                // Do not allow "android" is being disabled
14970                if ("android".equals(packageName)) {
14971                    Slog.w(TAG, "Cannot hide package: android");
14972                    return false;
14973                }
14974                // Cannot hide static shared libs as they are considered
14975                // a part of the using app (emulating static linking). Also
14976                // static libs are installed always on internal storage.
14977                PackageParser.Package pkg = mPackages.get(packageName);
14978                if (pkg != null && pkg.staticSharedLibName != null) {
14979                    Slog.w(TAG, "Cannot hide package: " + packageName
14980                            + " providing static shared library: "
14981                            + pkg.staticSharedLibName);
14982                    return false;
14983                }
14984                // Only allow protected packages to hide themselves.
14985                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14986                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14987                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14988                    return false;
14989                }
14990
14991                if (pkgSetting.getHidden(userId) != hidden) {
14992                    pkgSetting.setHidden(hidden, userId);
14993                    mSettings.writePackageRestrictionsLPr(userId);
14994                    if (hidden) {
14995                        sendRemoved = true;
14996                    } else {
14997                        sendAdded = true;
14998                    }
14999                }
15000            }
15001            if (sendAdded) {
15002                sendPackageAddedForUser(packageName, pkgSetting, userId);
15003                return true;
15004            }
15005            if (sendRemoved) {
15006                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
15007                        "hiding pkg");
15008                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
15009                return true;
15010            }
15011        } finally {
15012            Binder.restoreCallingIdentity(callingId);
15013        }
15014        return false;
15015    }
15016
15017    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
15018            int userId) {
15019        final PackageRemovedInfo info = new PackageRemovedInfo(this);
15020        info.removedPackage = packageName;
15021        info.installerPackageName = pkgSetting.installerPackageName;
15022        info.removedUsers = new int[] {userId};
15023        info.broadcastUsers = new int[] {userId};
15024        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
15025        info.sendPackageRemovedBroadcasts(true /*killApp*/);
15026    }
15027
15028    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
15029        if (pkgList.length > 0) {
15030            Bundle extras = new Bundle(1);
15031            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15032
15033            sendPackageBroadcast(
15034                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
15035                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
15036                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
15037                    new int[] {userId});
15038        }
15039    }
15040
15041    /**
15042     * Returns true if application is not found or there was an error. Otherwise it returns
15043     * the hidden state of the package for the given user.
15044     */
15045    @Override
15046    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
15047        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15048        final int callingUid = Binder.getCallingUid();
15049        enforceCrossUserPermission(callingUid, userId,
15050                true /* requireFullPermission */, false /* checkShell */,
15051                "getApplicationHidden for user " + userId);
15052        PackageSetting ps;
15053        long callingId = Binder.clearCallingIdentity();
15054        try {
15055            // writer
15056            synchronized (mPackages) {
15057                ps = mSettings.mPackages.get(packageName);
15058                if (ps == null) {
15059                    return true;
15060                }
15061                if (filterAppAccessLPr(ps, callingUid, userId)) {
15062                    return true;
15063                }
15064                return ps.getHidden(userId);
15065            }
15066        } finally {
15067            Binder.restoreCallingIdentity(callingId);
15068        }
15069    }
15070
15071    /**
15072     * @hide
15073     */
15074    @Override
15075    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
15076            int installReason) {
15077        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
15078                null);
15079        PackageSetting pkgSetting;
15080        final int callingUid = Binder.getCallingUid();
15081        enforceCrossUserPermission(callingUid, userId,
15082                true /* requireFullPermission */, true /* checkShell */,
15083                "installExistingPackage for user " + userId);
15084        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
15085            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
15086        }
15087
15088        long callingId = Binder.clearCallingIdentity();
15089        try {
15090            boolean installed = false;
15091            final boolean instantApp =
15092                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15093            final boolean fullApp =
15094                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
15095
15096            // writer
15097            synchronized (mPackages) {
15098                pkgSetting = mSettings.mPackages.get(packageName);
15099                if (pkgSetting == null) {
15100                    return PackageManager.INSTALL_FAILED_INVALID_URI;
15101                }
15102                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15103                    // only allow the existing package to be used if it's installed as a full
15104                    // application for at least one user
15105                    boolean installAllowed = false;
15106                    for (int checkUserId : sUserManager.getUserIds()) {
15107                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15108                        if (installAllowed) {
15109                            break;
15110                        }
15111                    }
15112                    if (!installAllowed) {
15113                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15114                    }
15115                }
15116                if (!pkgSetting.getInstalled(userId)) {
15117                    pkgSetting.setInstalled(true, userId);
15118                    pkgSetting.setHidden(false, userId);
15119                    pkgSetting.setInstallReason(installReason, userId);
15120                    mSettings.writePackageRestrictionsLPr(userId);
15121                    mSettings.writeKernelMappingLPr(pkgSetting);
15122                    installed = true;
15123                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15124                    // upgrade app from instant to full; we don't allow app downgrade
15125                    installed = true;
15126                }
15127                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15128            }
15129
15130            if (installed) {
15131                if (pkgSetting.pkg != null) {
15132                    synchronized (mInstallLock) {
15133                        // We don't need to freeze for a brand new install
15134                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15135                    }
15136                }
15137                sendPackageAddedForUser(packageName, pkgSetting, userId);
15138                synchronized (mPackages) {
15139                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15140                }
15141            }
15142        } finally {
15143            Binder.restoreCallingIdentity(callingId);
15144        }
15145
15146        return PackageManager.INSTALL_SUCCEEDED;
15147    }
15148
15149    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15150            boolean instantApp, boolean fullApp) {
15151        // no state specified; do nothing
15152        if (!instantApp && !fullApp) {
15153            return;
15154        }
15155        if (userId != UserHandle.USER_ALL) {
15156            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15157                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15158            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15159                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15160            }
15161        } else {
15162            for (int currentUserId : sUserManager.getUserIds()) {
15163                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15164                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15165                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15166                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15167                }
15168            }
15169        }
15170    }
15171
15172    boolean isUserRestricted(int userId, String restrictionKey) {
15173        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15174        if (restrictions.getBoolean(restrictionKey, false)) {
15175            Log.w(TAG, "User is restricted: " + restrictionKey);
15176            return true;
15177        }
15178        return false;
15179    }
15180
15181    @Override
15182    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15183            int userId) {
15184        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15185        final int callingUid = Binder.getCallingUid();
15186        enforceCrossUserPermission(callingUid, userId,
15187                true /* requireFullPermission */, true /* checkShell */,
15188                "setPackagesSuspended for user " + userId);
15189
15190        if (ArrayUtils.isEmpty(packageNames)) {
15191            return packageNames;
15192        }
15193
15194        // List of package names for whom the suspended state has changed.
15195        List<String> changedPackages = new ArrayList<>(packageNames.length);
15196        // List of package names for whom the suspended state is not set as requested in this
15197        // method.
15198        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15199        long callingId = Binder.clearCallingIdentity();
15200        try {
15201            for (int i = 0; i < packageNames.length; i++) {
15202                String packageName = packageNames[i];
15203                boolean changed = false;
15204                final int appId;
15205                synchronized (mPackages) {
15206                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15207                    if (pkgSetting == null
15208                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15209                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15210                                + "\". Skipping suspending/un-suspending.");
15211                        unactionedPackages.add(packageName);
15212                        continue;
15213                    }
15214                    appId = pkgSetting.appId;
15215                    if (pkgSetting.getSuspended(userId) != suspended) {
15216                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15217                            unactionedPackages.add(packageName);
15218                            continue;
15219                        }
15220                        pkgSetting.setSuspended(suspended, userId);
15221                        mSettings.writePackageRestrictionsLPr(userId);
15222                        changed = true;
15223                        changedPackages.add(packageName);
15224                    }
15225                }
15226
15227                if (changed && suspended) {
15228                    killApplication(packageName, UserHandle.getUid(userId, appId),
15229                            "suspending package");
15230                }
15231            }
15232        } finally {
15233            Binder.restoreCallingIdentity(callingId);
15234        }
15235
15236        if (!changedPackages.isEmpty()) {
15237            sendPackagesSuspendedForUser(changedPackages.toArray(
15238                    new String[changedPackages.size()]), userId, suspended);
15239        }
15240
15241        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15242    }
15243
15244    @Override
15245    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15246        final int callingUid = Binder.getCallingUid();
15247        enforceCrossUserPermission(callingUid, userId,
15248                true /* requireFullPermission */, false /* checkShell */,
15249                "isPackageSuspendedForUser for user " + userId);
15250        synchronized (mPackages) {
15251            final PackageSetting ps = mSettings.mPackages.get(packageName);
15252            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15253                throw new IllegalArgumentException("Unknown target package: " + packageName);
15254            }
15255            return ps.getSuspended(userId);
15256        }
15257    }
15258
15259    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15260        if (isPackageDeviceAdmin(packageName, userId)) {
15261            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15262                    + "\": has an active device admin");
15263            return false;
15264        }
15265
15266        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15267        if (packageName.equals(activeLauncherPackageName)) {
15268            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15269                    + "\": contains the active launcher");
15270            return false;
15271        }
15272
15273        if (packageName.equals(mRequiredInstallerPackage)) {
15274            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15275                    + "\": required for package installation");
15276            return false;
15277        }
15278
15279        if (packageName.equals(mRequiredUninstallerPackage)) {
15280            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15281                    + "\": required for package uninstallation");
15282            return false;
15283        }
15284
15285        if (packageName.equals(mRequiredVerifierPackage)) {
15286            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15287                    + "\": required for package verification");
15288            return false;
15289        }
15290
15291        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15292            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15293                    + "\": is the default dialer");
15294            return false;
15295        }
15296
15297        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15298            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15299                    + "\": protected package");
15300            return false;
15301        }
15302
15303        // Cannot suspend static shared libs as they are considered
15304        // a part of the using app (emulating static linking). Also
15305        // static libs are installed always on internal storage.
15306        PackageParser.Package pkg = mPackages.get(packageName);
15307        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15308            Slog.w(TAG, "Cannot suspend package: " + packageName
15309                    + " providing static shared library: "
15310                    + pkg.staticSharedLibName);
15311            return false;
15312        }
15313
15314        return true;
15315    }
15316
15317    private String getActiveLauncherPackageName(int userId) {
15318        Intent intent = new Intent(Intent.ACTION_MAIN);
15319        intent.addCategory(Intent.CATEGORY_HOME);
15320        ResolveInfo resolveInfo = resolveIntent(
15321                intent,
15322                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15323                PackageManager.MATCH_DEFAULT_ONLY,
15324                userId);
15325
15326        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15327    }
15328
15329    private String getDefaultDialerPackageName(int userId) {
15330        synchronized (mPackages) {
15331            return mSettings.getDefaultDialerPackageNameLPw(userId);
15332        }
15333    }
15334
15335    @Override
15336    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15337        mContext.enforceCallingOrSelfPermission(
15338                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15339                "Only package verification agents can verify applications");
15340
15341        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15342        final PackageVerificationResponse response = new PackageVerificationResponse(
15343                verificationCode, Binder.getCallingUid());
15344        msg.arg1 = id;
15345        msg.obj = response;
15346        mHandler.sendMessage(msg);
15347    }
15348
15349    @Override
15350    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15351            long millisecondsToDelay) {
15352        mContext.enforceCallingOrSelfPermission(
15353                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15354                "Only package verification agents can extend verification timeouts");
15355
15356        final PackageVerificationState state = mPendingVerification.get(id);
15357        final PackageVerificationResponse response = new PackageVerificationResponse(
15358                verificationCodeAtTimeout, Binder.getCallingUid());
15359
15360        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15361            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15362        }
15363        if (millisecondsToDelay < 0) {
15364            millisecondsToDelay = 0;
15365        }
15366        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15367                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15368            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15369        }
15370
15371        if ((state != null) && !state.timeoutExtended()) {
15372            state.extendTimeout();
15373
15374            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15375            msg.arg1 = id;
15376            msg.obj = response;
15377            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15378        }
15379    }
15380
15381    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15382            int verificationCode, UserHandle user) {
15383        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15384        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15385        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15386        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15387        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15388
15389        mContext.sendBroadcastAsUser(intent, user,
15390                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15391    }
15392
15393    private ComponentName matchComponentForVerifier(String packageName,
15394            List<ResolveInfo> receivers) {
15395        ActivityInfo targetReceiver = null;
15396
15397        final int NR = receivers.size();
15398        for (int i = 0; i < NR; i++) {
15399            final ResolveInfo info = receivers.get(i);
15400            if (info.activityInfo == null) {
15401                continue;
15402            }
15403
15404            if (packageName.equals(info.activityInfo.packageName)) {
15405                targetReceiver = info.activityInfo;
15406                break;
15407            }
15408        }
15409
15410        if (targetReceiver == null) {
15411            return null;
15412        }
15413
15414        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15415    }
15416
15417    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15418            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15419        if (pkgInfo.verifiers.length == 0) {
15420            return null;
15421        }
15422
15423        final int N = pkgInfo.verifiers.length;
15424        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15425        for (int i = 0; i < N; i++) {
15426            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15427
15428            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15429                    receivers);
15430            if (comp == null) {
15431                continue;
15432            }
15433
15434            final int verifierUid = getUidForVerifier(verifierInfo);
15435            if (verifierUid == -1) {
15436                continue;
15437            }
15438
15439            if (DEBUG_VERIFY) {
15440                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15441                        + " with the correct signature");
15442            }
15443            sufficientVerifiers.add(comp);
15444            verificationState.addSufficientVerifier(verifierUid);
15445        }
15446
15447        return sufficientVerifiers;
15448    }
15449
15450    private int getUidForVerifier(VerifierInfo verifierInfo) {
15451        synchronized (mPackages) {
15452            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15453            if (pkg == null) {
15454                return -1;
15455            } else if (pkg.mSignatures.length != 1) {
15456                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15457                        + " has more than one signature; ignoring");
15458                return -1;
15459            }
15460
15461            /*
15462             * If the public key of the package's signature does not match
15463             * our expected public key, then this is a different package and
15464             * we should skip.
15465             */
15466
15467            final byte[] expectedPublicKey;
15468            try {
15469                final Signature verifierSig = pkg.mSignatures[0];
15470                final PublicKey publicKey = verifierSig.getPublicKey();
15471                expectedPublicKey = publicKey.getEncoded();
15472            } catch (CertificateException e) {
15473                return -1;
15474            }
15475
15476            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15477
15478            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15479                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15480                        + " does not have the expected public key; ignoring");
15481                return -1;
15482            }
15483
15484            return pkg.applicationInfo.uid;
15485        }
15486    }
15487
15488    @Override
15489    public void finishPackageInstall(int token, boolean didLaunch) {
15490        enforceSystemOrRoot("Only the system is allowed to finish installs");
15491
15492        if (DEBUG_INSTALL) {
15493            Slog.v(TAG, "BM finishing package install for " + token);
15494        }
15495        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15496
15497        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15498        mHandler.sendMessage(msg);
15499    }
15500
15501    /**
15502     * Get the verification agent timeout.  Used for both the APK verifier and the
15503     * intent filter verifier.
15504     *
15505     * @return verification timeout in milliseconds
15506     */
15507    private long getVerificationTimeout() {
15508        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15509                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15510                DEFAULT_VERIFICATION_TIMEOUT);
15511    }
15512
15513    /**
15514     * Get the default verification agent response code.
15515     *
15516     * @return default verification response code
15517     */
15518    private int getDefaultVerificationResponse(UserHandle user) {
15519        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15520            return PackageManager.VERIFICATION_REJECT;
15521        }
15522        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15523                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15524                DEFAULT_VERIFICATION_RESPONSE);
15525    }
15526
15527    /**
15528     * Check whether or not package verification has been enabled.
15529     *
15530     * @return true if verification should be performed
15531     */
15532    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15533        if (!DEFAULT_VERIFY_ENABLE) {
15534            return false;
15535        }
15536
15537        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15538
15539        // Check if installing from ADB
15540        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15541            // Do not run verification in a test harness environment
15542            if (ActivityManager.isRunningInTestHarness()) {
15543                return false;
15544            }
15545            if (ensureVerifyAppsEnabled) {
15546                return true;
15547            }
15548            // Check if the developer does not want package verification for ADB installs
15549            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15550                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15551                return false;
15552            }
15553        } else {
15554            // only when not installed from ADB, skip verification for instant apps when
15555            // the installer and verifier are the same.
15556            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15557                if (mInstantAppInstallerActivity != null
15558                        && mInstantAppInstallerActivity.packageName.equals(
15559                                mRequiredVerifierPackage)) {
15560                    try {
15561                        mContext.getSystemService(AppOpsManager.class)
15562                                .checkPackage(installerUid, mRequiredVerifierPackage);
15563                        if (DEBUG_VERIFY) {
15564                            Slog.i(TAG, "disable verification for instant app");
15565                        }
15566                        return false;
15567                    } catch (SecurityException ignore) { }
15568                }
15569            }
15570        }
15571
15572        if (ensureVerifyAppsEnabled) {
15573            return true;
15574        }
15575
15576        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15577                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15578    }
15579
15580    @Override
15581    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15582            throws RemoteException {
15583        mContext.enforceCallingOrSelfPermission(
15584                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15585                "Only intentfilter verification agents can verify applications");
15586
15587        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15588        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15589                Binder.getCallingUid(), verificationCode, failedDomains);
15590        msg.arg1 = id;
15591        msg.obj = response;
15592        mHandler.sendMessage(msg);
15593    }
15594
15595    @Override
15596    public int getIntentVerificationStatus(String packageName, int userId) {
15597        final int callingUid = Binder.getCallingUid();
15598        if (UserHandle.getUserId(callingUid) != userId) {
15599            mContext.enforceCallingOrSelfPermission(
15600                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15601                    "getIntentVerificationStatus" + userId);
15602        }
15603        if (getInstantAppPackageName(callingUid) != null) {
15604            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15605        }
15606        synchronized (mPackages) {
15607            final PackageSetting ps = mSettings.mPackages.get(packageName);
15608            if (ps == null
15609                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15610                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15611            }
15612            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15613        }
15614    }
15615
15616    @Override
15617    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15618        mContext.enforceCallingOrSelfPermission(
15619                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15620
15621        boolean result = false;
15622        synchronized (mPackages) {
15623            final PackageSetting ps = mSettings.mPackages.get(packageName);
15624            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15625                return false;
15626            }
15627            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15628        }
15629        if (result) {
15630            scheduleWritePackageRestrictionsLocked(userId);
15631        }
15632        return result;
15633    }
15634
15635    @Override
15636    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15637            String packageName) {
15638        final int callingUid = Binder.getCallingUid();
15639        if (getInstantAppPackageName(callingUid) != null) {
15640            return ParceledListSlice.emptyList();
15641        }
15642        synchronized (mPackages) {
15643            final PackageSetting ps = mSettings.mPackages.get(packageName);
15644            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15645                return ParceledListSlice.emptyList();
15646            }
15647            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15648        }
15649    }
15650
15651    @Override
15652    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15653        if (TextUtils.isEmpty(packageName)) {
15654            return ParceledListSlice.emptyList();
15655        }
15656        final int callingUid = Binder.getCallingUid();
15657        final int callingUserId = UserHandle.getUserId(callingUid);
15658        synchronized (mPackages) {
15659            PackageParser.Package pkg = mPackages.get(packageName);
15660            if (pkg == null || pkg.activities == null) {
15661                return ParceledListSlice.emptyList();
15662            }
15663            if (pkg.mExtras == null) {
15664                return ParceledListSlice.emptyList();
15665            }
15666            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15667            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15668                return ParceledListSlice.emptyList();
15669            }
15670            final int count = pkg.activities.size();
15671            ArrayList<IntentFilter> result = new ArrayList<>();
15672            for (int n=0; n<count; n++) {
15673                PackageParser.Activity activity = pkg.activities.get(n);
15674                if (activity.intents != null && activity.intents.size() > 0) {
15675                    result.addAll(activity.intents);
15676                }
15677            }
15678            return new ParceledListSlice<>(result);
15679        }
15680    }
15681
15682    @Override
15683    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15684        mContext.enforceCallingOrSelfPermission(
15685                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15686        if (UserHandle.getCallingUserId() != userId) {
15687            mContext.enforceCallingOrSelfPermission(
15688                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15689        }
15690
15691        synchronized (mPackages) {
15692            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15693            if (packageName != null) {
15694                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15695                        packageName, userId);
15696            }
15697            return result;
15698        }
15699    }
15700
15701    @Override
15702    public String getDefaultBrowserPackageName(int userId) {
15703        if (UserHandle.getCallingUserId() != userId) {
15704            mContext.enforceCallingOrSelfPermission(
15705                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15706        }
15707        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15708            return null;
15709        }
15710        synchronized (mPackages) {
15711            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15712        }
15713    }
15714
15715    /**
15716     * Get the "allow unknown sources" setting.
15717     *
15718     * @return the current "allow unknown sources" setting
15719     */
15720    private int getUnknownSourcesSettings() {
15721        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15722                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15723                -1);
15724    }
15725
15726    @Override
15727    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15728        final int callingUid = Binder.getCallingUid();
15729        if (getInstantAppPackageName(callingUid) != null) {
15730            return;
15731        }
15732        // writer
15733        synchronized (mPackages) {
15734            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15735            if (targetPackageSetting == null
15736                    || filterAppAccessLPr(
15737                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15738                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15739            }
15740
15741            PackageSetting installerPackageSetting;
15742            if (installerPackageName != null) {
15743                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15744                if (installerPackageSetting == null) {
15745                    throw new IllegalArgumentException("Unknown installer package: "
15746                            + installerPackageName);
15747                }
15748            } else {
15749                installerPackageSetting = null;
15750            }
15751
15752            Signature[] callerSignature;
15753            Object obj = mSettings.getUserIdLPr(callingUid);
15754            if (obj != null) {
15755                if (obj instanceof SharedUserSetting) {
15756                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15757                } else if (obj instanceof PackageSetting) {
15758                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15759                } else {
15760                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15761                }
15762            } else {
15763                throw new SecurityException("Unknown calling UID: " + callingUid);
15764            }
15765
15766            // Verify: can't set installerPackageName to a package that is
15767            // not signed with the same cert as the caller.
15768            if (installerPackageSetting != null) {
15769                if (compareSignatures(callerSignature,
15770                        installerPackageSetting.signatures.mSignatures)
15771                        != PackageManager.SIGNATURE_MATCH) {
15772                    throw new SecurityException(
15773                            "Caller does not have same cert as new installer package "
15774                            + installerPackageName);
15775                }
15776            }
15777
15778            // Verify: if target already has an installer package, it must
15779            // be signed with the same cert as the caller.
15780            if (targetPackageSetting.installerPackageName != null) {
15781                PackageSetting setting = mSettings.mPackages.get(
15782                        targetPackageSetting.installerPackageName);
15783                // If the currently set package isn't valid, then it's always
15784                // okay to change it.
15785                if (setting != null) {
15786                    if (compareSignatures(callerSignature,
15787                            setting.signatures.mSignatures)
15788                            != PackageManager.SIGNATURE_MATCH) {
15789                        throw new SecurityException(
15790                                "Caller does not have same cert as old installer package "
15791                                + targetPackageSetting.installerPackageName);
15792                    }
15793                }
15794            }
15795
15796            // Okay!
15797            targetPackageSetting.installerPackageName = installerPackageName;
15798            if (installerPackageName != null) {
15799                mSettings.mInstallerPackages.add(installerPackageName);
15800            }
15801            scheduleWriteSettingsLocked();
15802        }
15803    }
15804
15805    @Override
15806    public void setApplicationCategoryHint(String packageName, int categoryHint,
15807            String callerPackageName) {
15808        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15809            throw new SecurityException("Instant applications don't have access to this method");
15810        }
15811        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15812                callerPackageName);
15813        synchronized (mPackages) {
15814            PackageSetting ps = mSettings.mPackages.get(packageName);
15815            if (ps == null) {
15816                throw new IllegalArgumentException("Unknown target package " + packageName);
15817            }
15818            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15819                throw new IllegalArgumentException("Unknown target package " + packageName);
15820            }
15821            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15822                throw new IllegalArgumentException("Calling package " + callerPackageName
15823                        + " is not installer for " + packageName);
15824            }
15825
15826            if (ps.categoryHint != categoryHint) {
15827                ps.categoryHint = categoryHint;
15828                scheduleWriteSettingsLocked();
15829            }
15830        }
15831    }
15832
15833    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15834        // Queue up an async operation since the package installation may take a little while.
15835        mHandler.post(new Runnable() {
15836            public void run() {
15837                mHandler.removeCallbacks(this);
15838                 // Result object to be returned
15839                PackageInstalledInfo res = new PackageInstalledInfo();
15840                res.setReturnCode(currentStatus);
15841                res.uid = -1;
15842                res.pkg = null;
15843                res.removedInfo = null;
15844                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15845                    args.doPreInstall(res.returnCode);
15846                    synchronized (mInstallLock) {
15847                        installPackageTracedLI(args, res);
15848                    }
15849                    args.doPostInstall(res.returnCode, res.uid);
15850                }
15851
15852                // A restore should be performed at this point if (a) the install
15853                // succeeded, (b) the operation is not an update, and (c) the new
15854                // package has not opted out of backup participation.
15855                final boolean update = res.removedInfo != null
15856                        && res.removedInfo.removedPackage != null;
15857                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15858                boolean doRestore = !update
15859                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15860
15861                // Set up the post-install work request bookkeeping.  This will be used
15862                // and cleaned up by the post-install event handling regardless of whether
15863                // there's a restore pass performed.  Token values are >= 1.
15864                int token;
15865                if (mNextInstallToken < 0) mNextInstallToken = 1;
15866                token = mNextInstallToken++;
15867
15868                PostInstallData data = new PostInstallData(args, res);
15869                mRunningInstalls.put(token, data);
15870                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15871
15872                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15873                    // Pass responsibility to the Backup Manager.  It will perform a
15874                    // restore if appropriate, then pass responsibility back to the
15875                    // Package Manager to run the post-install observer callbacks
15876                    // and broadcasts.
15877                    IBackupManager bm = IBackupManager.Stub.asInterface(
15878                            ServiceManager.getService(Context.BACKUP_SERVICE));
15879                    if (bm != null) {
15880                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15881                                + " to BM for possible restore");
15882                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15883                        try {
15884                            // TODO: http://b/22388012
15885                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15886                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15887                            } else {
15888                                doRestore = false;
15889                            }
15890                        } catch (RemoteException e) {
15891                            // can't happen; the backup manager is local
15892                        } catch (Exception e) {
15893                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15894                            doRestore = false;
15895                        }
15896                    } else {
15897                        Slog.e(TAG, "Backup Manager not found!");
15898                        doRestore = false;
15899                    }
15900                }
15901
15902                if (!doRestore) {
15903                    // No restore possible, or the Backup Manager was mysteriously not
15904                    // available -- just fire the post-install work request directly.
15905                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15906
15907                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15908
15909                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15910                    mHandler.sendMessage(msg);
15911                }
15912            }
15913        });
15914    }
15915
15916    /**
15917     * Callback from PackageSettings whenever an app is first transitioned out of the
15918     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15919     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15920     * here whether the app is the target of an ongoing install, and only send the
15921     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15922     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15923     * handling.
15924     */
15925    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15926        // Serialize this with the rest of the install-process message chain.  In the
15927        // restore-at-install case, this Runnable will necessarily run before the
15928        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15929        // are coherent.  In the non-restore case, the app has already completed install
15930        // and been launched through some other means, so it is not in a problematic
15931        // state for observers to see the FIRST_LAUNCH signal.
15932        mHandler.post(new Runnable() {
15933            @Override
15934            public void run() {
15935                for (int i = 0; i < mRunningInstalls.size(); i++) {
15936                    final PostInstallData data = mRunningInstalls.valueAt(i);
15937                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15938                        continue;
15939                    }
15940                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15941                        // right package; but is it for the right user?
15942                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15943                            if (userId == data.res.newUsers[uIndex]) {
15944                                if (DEBUG_BACKUP) {
15945                                    Slog.i(TAG, "Package " + pkgName
15946                                            + " being restored so deferring FIRST_LAUNCH");
15947                                }
15948                                return;
15949                            }
15950                        }
15951                    }
15952                }
15953                // didn't find it, so not being restored
15954                if (DEBUG_BACKUP) {
15955                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15956                }
15957                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15958            }
15959        });
15960    }
15961
15962    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15963        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15964                installerPkg, null, userIds);
15965    }
15966
15967    private abstract class HandlerParams {
15968        private static final int MAX_RETRIES = 4;
15969
15970        /**
15971         * Number of times startCopy() has been attempted and had a non-fatal
15972         * error.
15973         */
15974        private int mRetries = 0;
15975
15976        /** User handle for the user requesting the information or installation. */
15977        private final UserHandle mUser;
15978        String traceMethod;
15979        int traceCookie;
15980
15981        HandlerParams(UserHandle user) {
15982            mUser = user;
15983        }
15984
15985        UserHandle getUser() {
15986            return mUser;
15987        }
15988
15989        HandlerParams setTraceMethod(String traceMethod) {
15990            this.traceMethod = traceMethod;
15991            return this;
15992        }
15993
15994        HandlerParams setTraceCookie(int traceCookie) {
15995            this.traceCookie = traceCookie;
15996            return this;
15997        }
15998
15999        final boolean startCopy() {
16000            boolean res;
16001            try {
16002                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
16003
16004                if (++mRetries > MAX_RETRIES) {
16005                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
16006                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
16007                    handleServiceError();
16008                    return false;
16009                } else {
16010                    handleStartCopy();
16011                    res = true;
16012                }
16013            } catch (RemoteException e) {
16014                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
16015                mHandler.sendEmptyMessage(MCS_RECONNECT);
16016                res = false;
16017            }
16018            handleReturnCode();
16019            return res;
16020        }
16021
16022        final void serviceError() {
16023            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
16024            handleServiceError();
16025            handleReturnCode();
16026        }
16027
16028        abstract void handleStartCopy() throws RemoteException;
16029        abstract void handleServiceError();
16030        abstract void handleReturnCode();
16031    }
16032
16033    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
16034        for (File path : paths) {
16035            try {
16036                mcs.clearDirectory(path.getAbsolutePath());
16037            } catch (RemoteException e) {
16038            }
16039        }
16040    }
16041
16042    static class OriginInfo {
16043        /**
16044         * Location where install is coming from, before it has been
16045         * copied/renamed into place. This could be a single monolithic APK
16046         * file, or a cluster directory. This location may be untrusted.
16047         */
16048        final File file;
16049        final String cid;
16050
16051        /**
16052         * Flag indicating that {@link #file} or {@link #cid} has already been
16053         * staged, meaning downstream users don't need to defensively copy the
16054         * contents.
16055         */
16056        final boolean staged;
16057
16058        /**
16059         * Flag indicating that {@link #file} or {@link #cid} is an already
16060         * installed app that is being moved.
16061         */
16062        final boolean existing;
16063
16064        final String resolvedPath;
16065        final File resolvedFile;
16066
16067        static OriginInfo fromNothing() {
16068            return new OriginInfo(null, null, false, false);
16069        }
16070
16071        static OriginInfo fromUntrustedFile(File file) {
16072            return new OriginInfo(file, null, false, false);
16073        }
16074
16075        static OriginInfo fromExistingFile(File file) {
16076            return new OriginInfo(file, null, false, true);
16077        }
16078
16079        static OriginInfo fromStagedFile(File file) {
16080            return new OriginInfo(file, null, true, false);
16081        }
16082
16083        static OriginInfo fromStagedContainer(String cid) {
16084            return new OriginInfo(null, cid, true, false);
16085        }
16086
16087        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
16088            this.file = file;
16089            this.cid = cid;
16090            this.staged = staged;
16091            this.existing = existing;
16092
16093            if (cid != null) {
16094                resolvedPath = PackageHelper.getSdDir(cid);
16095                resolvedFile = new File(resolvedPath);
16096            } else if (file != null) {
16097                resolvedPath = file.getAbsolutePath();
16098                resolvedFile = file;
16099            } else {
16100                resolvedPath = null;
16101                resolvedFile = null;
16102            }
16103        }
16104    }
16105
16106    static class MoveInfo {
16107        final int moveId;
16108        final String fromUuid;
16109        final String toUuid;
16110        final String packageName;
16111        final String dataAppName;
16112        final int appId;
16113        final String seinfo;
16114        final int targetSdkVersion;
16115
16116        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16117                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16118            this.moveId = moveId;
16119            this.fromUuid = fromUuid;
16120            this.toUuid = toUuid;
16121            this.packageName = packageName;
16122            this.dataAppName = dataAppName;
16123            this.appId = appId;
16124            this.seinfo = seinfo;
16125            this.targetSdkVersion = targetSdkVersion;
16126        }
16127    }
16128
16129    static class VerificationInfo {
16130        /** A constant used to indicate that a uid value is not present. */
16131        public static final int NO_UID = -1;
16132
16133        /** URI referencing where the package was downloaded from. */
16134        final Uri originatingUri;
16135
16136        /** HTTP referrer URI associated with the originatingURI. */
16137        final Uri referrer;
16138
16139        /** UID of the application that the install request originated from. */
16140        final int originatingUid;
16141
16142        /** UID of application requesting the install */
16143        final int installerUid;
16144
16145        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16146            this.originatingUri = originatingUri;
16147            this.referrer = referrer;
16148            this.originatingUid = originatingUid;
16149            this.installerUid = installerUid;
16150        }
16151    }
16152
16153    class InstallParams extends HandlerParams {
16154        final OriginInfo origin;
16155        final MoveInfo move;
16156        final IPackageInstallObserver2 observer;
16157        int installFlags;
16158        final String installerPackageName;
16159        final String volumeUuid;
16160        private InstallArgs mArgs;
16161        private int mRet;
16162        final String packageAbiOverride;
16163        final String[] grantedRuntimePermissions;
16164        final VerificationInfo verificationInfo;
16165        final Certificate[][] certificates;
16166        final int installReason;
16167
16168        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16169                int installFlags, String installerPackageName, String volumeUuid,
16170                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16171                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16172            super(user);
16173            this.origin = origin;
16174            this.move = move;
16175            this.observer = observer;
16176            this.installFlags = installFlags;
16177            this.installerPackageName = installerPackageName;
16178            this.volumeUuid = volumeUuid;
16179            this.verificationInfo = verificationInfo;
16180            this.packageAbiOverride = packageAbiOverride;
16181            this.grantedRuntimePermissions = grantedPermissions;
16182            this.certificates = certificates;
16183            this.installReason = installReason;
16184        }
16185
16186        @Override
16187        public String toString() {
16188            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16189                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16190        }
16191
16192        private int installLocationPolicy(PackageInfoLite pkgLite) {
16193            String packageName = pkgLite.packageName;
16194            int installLocation = pkgLite.installLocation;
16195            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16196            // reader
16197            synchronized (mPackages) {
16198                // Currently installed package which the new package is attempting to replace or
16199                // null if no such package is installed.
16200                PackageParser.Package installedPkg = mPackages.get(packageName);
16201                // Package which currently owns the data which the new package will own if installed.
16202                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16203                // will be null whereas dataOwnerPkg will contain information about the package
16204                // which was uninstalled while keeping its data.
16205                PackageParser.Package dataOwnerPkg = installedPkg;
16206                if (dataOwnerPkg  == null) {
16207                    PackageSetting ps = mSettings.mPackages.get(packageName);
16208                    if (ps != null) {
16209                        dataOwnerPkg = ps.pkg;
16210                    }
16211                }
16212
16213                if (dataOwnerPkg != null) {
16214                    // If installed, the package will get access to data left on the device by its
16215                    // predecessor. As a security measure, this is permited only if this is not a
16216                    // version downgrade or if the predecessor package is marked as debuggable and
16217                    // a downgrade is explicitly requested.
16218                    //
16219                    // On debuggable platform builds, downgrades are permitted even for
16220                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16221                    // not offer security guarantees and thus it's OK to disable some security
16222                    // mechanisms to make debugging/testing easier on those builds. However, even on
16223                    // debuggable builds downgrades of packages are permitted only if requested via
16224                    // installFlags. This is because we aim to keep the behavior of debuggable
16225                    // platform builds as close as possible to the behavior of non-debuggable
16226                    // platform builds.
16227                    final boolean downgradeRequested =
16228                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16229                    final boolean packageDebuggable =
16230                                (dataOwnerPkg.applicationInfo.flags
16231                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16232                    final boolean downgradePermitted =
16233                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16234                    if (!downgradePermitted) {
16235                        try {
16236                            checkDowngrade(dataOwnerPkg, pkgLite);
16237                        } catch (PackageManagerException e) {
16238                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16239                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16240                        }
16241                    }
16242                }
16243
16244                if (installedPkg != null) {
16245                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16246                        // Check for updated system application.
16247                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16248                            if (onSd) {
16249                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16250                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16251                            }
16252                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16253                        } else {
16254                            if (onSd) {
16255                                // Install flag overrides everything.
16256                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16257                            }
16258                            // If current upgrade specifies particular preference
16259                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16260                                // Application explicitly specified internal.
16261                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16262                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16263                                // App explictly prefers external. Let policy decide
16264                            } else {
16265                                // Prefer previous location
16266                                if (isExternal(installedPkg)) {
16267                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16268                                }
16269                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16270                            }
16271                        }
16272                    } else {
16273                        // Invalid install. Return error code
16274                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16275                    }
16276                }
16277            }
16278            // All the special cases have been taken care of.
16279            // Return result based on recommended install location.
16280            if (onSd) {
16281                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16282            }
16283            return pkgLite.recommendedInstallLocation;
16284        }
16285
16286        /*
16287         * Invoke remote method to get package information and install
16288         * location values. Override install location based on default
16289         * policy if needed and then create install arguments based
16290         * on the install location.
16291         */
16292        public void handleStartCopy() throws RemoteException {
16293            int ret = PackageManager.INSTALL_SUCCEEDED;
16294
16295            // If we're already staged, we've firmly committed to an install location
16296            if (origin.staged) {
16297                if (origin.file != null) {
16298                    installFlags |= PackageManager.INSTALL_INTERNAL;
16299                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16300                } else if (origin.cid != null) {
16301                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16302                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16303                } else {
16304                    throw new IllegalStateException("Invalid stage location");
16305                }
16306            }
16307
16308            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16309            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16310            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16311            PackageInfoLite pkgLite = null;
16312
16313            if (onInt && onSd) {
16314                // Check if both bits are set.
16315                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16316                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16317            } else if (onSd && ephemeral) {
16318                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16319                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16320            } else {
16321                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16322                        packageAbiOverride);
16323
16324                if (DEBUG_EPHEMERAL && ephemeral) {
16325                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16326                }
16327
16328                /*
16329                 * If we have too little free space, try to free cache
16330                 * before giving up.
16331                 */
16332                if (!origin.staged && pkgLite.recommendedInstallLocation
16333                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16334                    // TODO: focus freeing disk space on the target device
16335                    final StorageManager storage = StorageManager.from(mContext);
16336                    final long lowThreshold = storage.getStorageLowBytes(
16337                            Environment.getDataDirectory());
16338
16339                    final long sizeBytes = mContainerService.calculateInstalledSize(
16340                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16341
16342                    try {
16343                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16344                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16345                                installFlags, packageAbiOverride);
16346                    } catch (InstallerException e) {
16347                        Slog.w(TAG, "Failed to free cache", e);
16348                    }
16349
16350                    /*
16351                     * The cache free must have deleted the file we
16352                     * downloaded to install.
16353                     *
16354                     * TODO: fix the "freeCache" call to not delete
16355                     *       the file we care about.
16356                     */
16357                    if (pkgLite.recommendedInstallLocation
16358                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16359                        pkgLite.recommendedInstallLocation
16360                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16361                    }
16362                }
16363            }
16364
16365            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16366                int loc = pkgLite.recommendedInstallLocation;
16367                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16368                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16369                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16370                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16371                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16372                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16373                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16374                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16375                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16376                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16377                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16378                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16379                } else {
16380                    // Override with defaults if needed.
16381                    loc = installLocationPolicy(pkgLite);
16382                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16383                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16384                    } else if (!onSd && !onInt) {
16385                        // Override install location with flags
16386                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16387                            // Set the flag to install on external media.
16388                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16389                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16390                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16391                            if (DEBUG_EPHEMERAL) {
16392                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16393                            }
16394                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16395                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16396                                    |PackageManager.INSTALL_INTERNAL);
16397                        } else {
16398                            // Make sure the flag for installing on external
16399                            // media is unset
16400                            installFlags |= PackageManager.INSTALL_INTERNAL;
16401                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16402                        }
16403                    }
16404                }
16405            }
16406
16407            final InstallArgs args = createInstallArgs(this);
16408            mArgs = args;
16409
16410            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16411                // TODO: http://b/22976637
16412                // Apps installed for "all" users use the device owner to verify the app
16413                UserHandle verifierUser = getUser();
16414                if (verifierUser == UserHandle.ALL) {
16415                    verifierUser = UserHandle.SYSTEM;
16416                }
16417
16418                /*
16419                 * Determine if we have any installed package verifiers. If we
16420                 * do, then we'll defer to them to verify the packages.
16421                 */
16422                final int requiredUid = mRequiredVerifierPackage == null ? -1
16423                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16424                                verifierUser.getIdentifier());
16425                final int installerUid =
16426                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16427                if (!origin.existing && requiredUid != -1
16428                        && isVerificationEnabled(
16429                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16430                    final Intent verification = new Intent(
16431                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16432                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16433                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16434                            PACKAGE_MIME_TYPE);
16435                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16436
16437                    // Query all live verifiers based on current user state
16438                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16439                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16440                            false /*allowDynamicSplits*/);
16441
16442                    if (DEBUG_VERIFY) {
16443                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16444                                + verification.toString() + " with " + pkgLite.verifiers.length
16445                                + " optional verifiers");
16446                    }
16447
16448                    final int verificationId = mPendingVerificationToken++;
16449
16450                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16451
16452                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16453                            installerPackageName);
16454
16455                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16456                            installFlags);
16457
16458                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16459                            pkgLite.packageName);
16460
16461                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16462                            pkgLite.versionCode);
16463
16464                    if (verificationInfo != null) {
16465                        if (verificationInfo.originatingUri != null) {
16466                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16467                                    verificationInfo.originatingUri);
16468                        }
16469                        if (verificationInfo.referrer != null) {
16470                            verification.putExtra(Intent.EXTRA_REFERRER,
16471                                    verificationInfo.referrer);
16472                        }
16473                        if (verificationInfo.originatingUid >= 0) {
16474                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16475                                    verificationInfo.originatingUid);
16476                        }
16477                        if (verificationInfo.installerUid >= 0) {
16478                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16479                                    verificationInfo.installerUid);
16480                        }
16481                    }
16482
16483                    final PackageVerificationState verificationState = new PackageVerificationState(
16484                            requiredUid, args);
16485
16486                    mPendingVerification.append(verificationId, verificationState);
16487
16488                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16489                            receivers, verificationState);
16490
16491                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16492                    final long idleDuration = getVerificationTimeout();
16493
16494                    /*
16495                     * If any sufficient verifiers were listed in the package
16496                     * manifest, attempt to ask them.
16497                     */
16498                    if (sufficientVerifiers != null) {
16499                        final int N = sufficientVerifiers.size();
16500                        if (N == 0) {
16501                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16502                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16503                        } else {
16504                            for (int i = 0; i < N; i++) {
16505                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16506                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16507                                        verifierComponent.getPackageName(), idleDuration,
16508                                        verifierUser.getIdentifier(), false, "package verifier");
16509
16510                                final Intent sufficientIntent = new Intent(verification);
16511                                sufficientIntent.setComponent(verifierComponent);
16512                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16513                            }
16514                        }
16515                    }
16516
16517                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16518                            mRequiredVerifierPackage, receivers);
16519                    if (ret == PackageManager.INSTALL_SUCCEEDED
16520                            && mRequiredVerifierPackage != null) {
16521                        Trace.asyncTraceBegin(
16522                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16523                        /*
16524                         * Send the intent to the required verification agent,
16525                         * but only start the verification timeout after the
16526                         * target BroadcastReceivers have run.
16527                         */
16528                        verification.setComponent(requiredVerifierComponent);
16529                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16530                                mRequiredVerifierPackage, idleDuration,
16531                                verifierUser.getIdentifier(), false, "package verifier");
16532                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16533                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16534                                new BroadcastReceiver() {
16535                                    @Override
16536                                    public void onReceive(Context context, Intent intent) {
16537                                        final Message msg = mHandler
16538                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16539                                        msg.arg1 = verificationId;
16540                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16541                                    }
16542                                }, null, 0, null, null);
16543
16544                        /*
16545                         * We don't want the copy to proceed until verification
16546                         * succeeds, so null out this field.
16547                         */
16548                        mArgs = null;
16549                    }
16550                } else {
16551                    /*
16552                     * No package verification is enabled, so immediately start
16553                     * the remote call to initiate copy using temporary file.
16554                     */
16555                    ret = args.copyApk(mContainerService, true);
16556                }
16557            }
16558
16559            mRet = ret;
16560        }
16561
16562        @Override
16563        void handleReturnCode() {
16564            // If mArgs is null, then MCS couldn't be reached. When it
16565            // reconnects, it will try again to install. At that point, this
16566            // will succeed.
16567            if (mArgs != null) {
16568                processPendingInstall(mArgs, mRet);
16569            }
16570        }
16571
16572        @Override
16573        void handleServiceError() {
16574            mArgs = createInstallArgs(this);
16575            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16576        }
16577
16578        public boolean isForwardLocked() {
16579            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16580        }
16581    }
16582
16583    /**
16584     * Used during creation of InstallArgs
16585     *
16586     * @param installFlags package installation flags
16587     * @return true if should be installed on external storage
16588     */
16589    private static boolean installOnExternalAsec(int installFlags) {
16590        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16591            return false;
16592        }
16593        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16594            return true;
16595        }
16596        return false;
16597    }
16598
16599    /**
16600     * Used during creation of InstallArgs
16601     *
16602     * @param installFlags package installation flags
16603     * @return true if should be installed as forward locked
16604     */
16605    private static boolean installForwardLocked(int installFlags) {
16606        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16607    }
16608
16609    private InstallArgs createInstallArgs(InstallParams params) {
16610        if (params.move != null) {
16611            return new MoveInstallArgs(params);
16612        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16613            return new AsecInstallArgs(params);
16614        } else {
16615            return new FileInstallArgs(params);
16616        }
16617    }
16618
16619    /**
16620     * Create args that describe an existing installed package. Typically used
16621     * when cleaning up old installs, or used as a move source.
16622     */
16623    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16624            String resourcePath, String[] instructionSets) {
16625        final boolean isInAsec;
16626        if (installOnExternalAsec(installFlags)) {
16627            /* Apps on SD card are always in ASEC containers. */
16628            isInAsec = true;
16629        } else if (installForwardLocked(installFlags)
16630                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16631            /*
16632             * Forward-locked apps are only in ASEC containers if they're the
16633             * new style
16634             */
16635            isInAsec = true;
16636        } else {
16637            isInAsec = false;
16638        }
16639
16640        if (isInAsec) {
16641            return new AsecInstallArgs(codePath, instructionSets,
16642                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16643        } else {
16644            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16645        }
16646    }
16647
16648    static abstract class InstallArgs {
16649        /** @see InstallParams#origin */
16650        final OriginInfo origin;
16651        /** @see InstallParams#move */
16652        final MoveInfo move;
16653
16654        final IPackageInstallObserver2 observer;
16655        // Always refers to PackageManager flags only
16656        final int installFlags;
16657        final String installerPackageName;
16658        final String volumeUuid;
16659        final UserHandle user;
16660        final String abiOverride;
16661        final String[] installGrantPermissions;
16662        /** If non-null, drop an async trace when the install completes */
16663        final String traceMethod;
16664        final int traceCookie;
16665        final Certificate[][] certificates;
16666        final int installReason;
16667
16668        // The list of instruction sets supported by this app. This is currently
16669        // only used during the rmdex() phase to clean up resources. We can get rid of this
16670        // if we move dex files under the common app path.
16671        /* nullable */ String[] instructionSets;
16672
16673        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16674                int installFlags, String installerPackageName, String volumeUuid,
16675                UserHandle user, String[] instructionSets,
16676                String abiOverride, String[] installGrantPermissions,
16677                String traceMethod, int traceCookie, Certificate[][] certificates,
16678                int installReason) {
16679            this.origin = origin;
16680            this.move = move;
16681            this.installFlags = installFlags;
16682            this.observer = observer;
16683            this.installerPackageName = installerPackageName;
16684            this.volumeUuid = volumeUuid;
16685            this.user = user;
16686            this.instructionSets = instructionSets;
16687            this.abiOverride = abiOverride;
16688            this.installGrantPermissions = installGrantPermissions;
16689            this.traceMethod = traceMethod;
16690            this.traceCookie = traceCookie;
16691            this.certificates = certificates;
16692            this.installReason = installReason;
16693        }
16694
16695        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16696        abstract int doPreInstall(int status);
16697
16698        /**
16699         * Rename package into final resting place. All paths on the given
16700         * scanned package should be updated to reflect the rename.
16701         */
16702        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16703        abstract int doPostInstall(int status, int uid);
16704
16705        /** @see PackageSettingBase#codePathString */
16706        abstract String getCodePath();
16707        /** @see PackageSettingBase#resourcePathString */
16708        abstract String getResourcePath();
16709
16710        // Need installer lock especially for dex file removal.
16711        abstract void cleanUpResourcesLI();
16712        abstract boolean doPostDeleteLI(boolean delete);
16713
16714        /**
16715         * Called before the source arguments are copied. This is used mostly
16716         * for MoveParams when it needs to read the source file to put it in the
16717         * destination.
16718         */
16719        int doPreCopy() {
16720            return PackageManager.INSTALL_SUCCEEDED;
16721        }
16722
16723        /**
16724         * Called after the source arguments are copied. This is used mostly for
16725         * MoveParams when it needs to read the source file to put it in the
16726         * destination.
16727         */
16728        int doPostCopy(int uid) {
16729            return PackageManager.INSTALL_SUCCEEDED;
16730        }
16731
16732        protected boolean isFwdLocked() {
16733            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16734        }
16735
16736        protected boolean isExternalAsec() {
16737            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16738        }
16739
16740        protected boolean isEphemeral() {
16741            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16742        }
16743
16744        UserHandle getUser() {
16745            return user;
16746        }
16747    }
16748
16749    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16750        if (!allCodePaths.isEmpty()) {
16751            if (instructionSets == null) {
16752                throw new IllegalStateException("instructionSet == null");
16753            }
16754            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16755            for (String codePath : allCodePaths) {
16756                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16757                    try {
16758                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16759                    } catch (InstallerException ignored) {
16760                    }
16761                }
16762            }
16763        }
16764    }
16765
16766    /**
16767     * Logic to handle installation of non-ASEC applications, including copying
16768     * and renaming logic.
16769     */
16770    class FileInstallArgs extends InstallArgs {
16771        private File codeFile;
16772        private File resourceFile;
16773
16774        // Example topology:
16775        // /data/app/com.example/base.apk
16776        // /data/app/com.example/split_foo.apk
16777        // /data/app/com.example/lib/arm/libfoo.so
16778        // /data/app/com.example/lib/arm64/libfoo.so
16779        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16780
16781        /** New install */
16782        FileInstallArgs(InstallParams params) {
16783            super(params.origin, params.move, params.observer, params.installFlags,
16784                    params.installerPackageName, params.volumeUuid,
16785                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16786                    params.grantedRuntimePermissions,
16787                    params.traceMethod, params.traceCookie, params.certificates,
16788                    params.installReason);
16789            if (isFwdLocked()) {
16790                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16791            }
16792        }
16793
16794        /** Existing install */
16795        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16796            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16797                    null, null, null, 0, null /*certificates*/,
16798                    PackageManager.INSTALL_REASON_UNKNOWN);
16799            this.codeFile = (codePath != null) ? new File(codePath) : null;
16800            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16801        }
16802
16803        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16804            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16805            try {
16806                return doCopyApk(imcs, temp);
16807            } finally {
16808                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16809            }
16810        }
16811
16812        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16813            if (origin.staged) {
16814                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16815                codeFile = origin.file;
16816                resourceFile = origin.file;
16817                return PackageManager.INSTALL_SUCCEEDED;
16818            }
16819
16820            try {
16821                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16822                final File tempDir =
16823                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16824                codeFile = tempDir;
16825                resourceFile = tempDir;
16826            } catch (IOException e) {
16827                Slog.w(TAG, "Failed to create copy file: " + e);
16828                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16829            }
16830
16831            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16832                @Override
16833                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16834                    if (!FileUtils.isValidExtFilename(name)) {
16835                        throw new IllegalArgumentException("Invalid filename: " + name);
16836                    }
16837                    try {
16838                        final File file = new File(codeFile, name);
16839                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16840                                O_RDWR | O_CREAT, 0644);
16841                        Os.chmod(file.getAbsolutePath(), 0644);
16842                        return new ParcelFileDescriptor(fd);
16843                    } catch (ErrnoException e) {
16844                        throw new RemoteException("Failed to open: " + e.getMessage());
16845                    }
16846                }
16847            };
16848
16849            int ret = PackageManager.INSTALL_SUCCEEDED;
16850            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16851            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16852                Slog.e(TAG, "Failed to copy package");
16853                return ret;
16854            }
16855
16856            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16857            NativeLibraryHelper.Handle handle = null;
16858            try {
16859                handle = NativeLibraryHelper.Handle.create(codeFile);
16860                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16861                        abiOverride);
16862            } catch (IOException e) {
16863                Slog.e(TAG, "Copying native libraries failed", e);
16864                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16865            } finally {
16866                IoUtils.closeQuietly(handle);
16867            }
16868
16869            return ret;
16870        }
16871
16872        int doPreInstall(int status) {
16873            if (status != PackageManager.INSTALL_SUCCEEDED) {
16874                cleanUp();
16875            }
16876            return status;
16877        }
16878
16879        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16880            if (status != PackageManager.INSTALL_SUCCEEDED) {
16881                cleanUp();
16882                return false;
16883            }
16884
16885            final File targetDir = codeFile.getParentFile();
16886            final File beforeCodeFile = codeFile;
16887            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16888
16889            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16890            try {
16891                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16892            } catch (ErrnoException e) {
16893                Slog.w(TAG, "Failed to rename", e);
16894                return false;
16895            }
16896
16897            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16898                Slog.w(TAG, "Failed to restorecon");
16899                return false;
16900            }
16901
16902            // Reflect the rename internally
16903            codeFile = afterCodeFile;
16904            resourceFile = afterCodeFile;
16905
16906            // Reflect the rename in scanned details
16907            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16908            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16909                    afterCodeFile, pkg.baseCodePath));
16910            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16911                    afterCodeFile, pkg.splitCodePaths));
16912
16913            // Reflect the rename in app info
16914            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16915            pkg.setApplicationInfoCodePath(pkg.codePath);
16916            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16917            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16918            pkg.setApplicationInfoResourcePath(pkg.codePath);
16919            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16920            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16921
16922            return true;
16923        }
16924
16925        int doPostInstall(int status, int uid) {
16926            if (status != PackageManager.INSTALL_SUCCEEDED) {
16927                cleanUp();
16928            }
16929            return status;
16930        }
16931
16932        @Override
16933        String getCodePath() {
16934            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16935        }
16936
16937        @Override
16938        String getResourcePath() {
16939            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16940        }
16941
16942        private boolean cleanUp() {
16943            if (codeFile == null || !codeFile.exists()) {
16944                return false;
16945            }
16946
16947            removeCodePathLI(codeFile);
16948
16949            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16950                resourceFile.delete();
16951            }
16952
16953            return true;
16954        }
16955
16956        void cleanUpResourcesLI() {
16957            // Try enumerating all code paths before deleting
16958            List<String> allCodePaths = Collections.EMPTY_LIST;
16959            if (codeFile != null && codeFile.exists()) {
16960                try {
16961                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16962                    allCodePaths = pkg.getAllCodePaths();
16963                } catch (PackageParserException e) {
16964                    // Ignored; we tried our best
16965                }
16966            }
16967
16968            cleanUp();
16969            removeDexFiles(allCodePaths, instructionSets);
16970        }
16971
16972        boolean doPostDeleteLI(boolean delete) {
16973            // XXX err, shouldn't we respect the delete flag?
16974            cleanUpResourcesLI();
16975            return true;
16976        }
16977    }
16978
16979    private boolean isAsecExternal(String cid) {
16980        final String asecPath = PackageHelper.getSdFilesystem(cid);
16981        return !asecPath.startsWith(mAsecInternalPath);
16982    }
16983
16984    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16985            PackageManagerException {
16986        if (copyRet < 0) {
16987            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16988                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16989                throw new PackageManagerException(copyRet, message);
16990            }
16991        }
16992    }
16993
16994    /**
16995     * Extract the StorageManagerService "container ID" from the full code path of an
16996     * .apk.
16997     */
16998    static String cidFromCodePath(String fullCodePath) {
16999        int eidx = fullCodePath.lastIndexOf("/");
17000        String subStr1 = fullCodePath.substring(0, eidx);
17001        int sidx = subStr1.lastIndexOf("/");
17002        return subStr1.substring(sidx+1, eidx);
17003    }
17004
17005    /**
17006     * Logic to handle installation of ASEC applications, including copying and
17007     * renaming logic.
17008     */
17009    class AsecInstallArgs extends InstallArgs {
17010        static final String RES_FILE_NAME = "pkg.apk";
17011        static final String PUBLIC_RES_FILE_NAME = "res.zip";
17012
17013        String cid;
17014        String packagePath;
17015        String resourcePath;
17016
17017        /** New install */
17018        AsecInstallArgs(InstallParams params) {
17019            super(params.origin, params.move, params.observer, params.installFlags,
17020                    params.installerPackageName, params.volumeUuid,
17021                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17022                    params.grantedRuntimePermissions,
17023                    params.traceMethod, params.traceCookie, params.certificates,
17024                    params.installReason);
17025        }
17026
17027        /** Existing install */
17028        AsecInstallArgs(String fullCodePath, String[] instructionSets,
17029                        boolean isExternal, boolean isForwardLocked) {
17030            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
17031                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17032                    instructionSets, null, null, null, 0, null /*certificates*/,
17033                    PackageManager.INSTALL_REASON_UNKNOWN);
17034            // Hackily pretend we're still looking at a full code path
17035            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
17036                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
17037            }
17038
17039            // Extract cid from fullCodePath
17040            int eidx = fullCodePath.lastIndexOf("/");
17041            String subStr1 = fullCodePath.substring(0, eidx);
17042            int sidx = subStr1.lastIndexOf("/");
17043            cid = subStr1.substring(sidx+1, eidx);
17044            setMountPath(subStr1);
17045        }
17046
17047        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
17048            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
17049                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17050                    instructionSets, null, null, null, 0, null /*certificates*/,
17051                    PackageManager.INSTALL_REASON_UNKNOWN);
17052            this.cid = cid;
17053            setMountPath(PackageHelper.getSdDir(cid));
17054        }
17055
17056        void createCopyFile() {
17057            cid = mInstallerService.allocateExternalStageCidLegacy();
17058        }
17059
17060        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
17061            if (origin.staged && origin.cid != null) {
17062                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
17063                cid = origin.cid;
17064                setMountPath(PackageHelper.getSdDir(cid));
17065                return PackageManager.INSTALL_SUCCEEDED;
17066            }
17067
17068            if (temp) {
17069                createCopyFile();
17070            } else {
17071                /*
17072                 * Pre-emptively destroy the container since it's destroyed if
17073                 * copying fails due to it existing anyway.
17074                 */
17075                PackageHelper.destroySdDir(cid);
17076            }
17077
17078            final String newMountPath = imcs.copyPackageToContainer(
17079                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
17080                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
17081
17082            if (newMountPath != null) {
17083                setMountPath(newMountPath);
17084                return PackageManager.INSTALL_SUCCEEDED;
17085            } else {
17086                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17087            }
17088        }
17089
17090        @Override
17091        String getCodePath() {
17092            return packagePath;
17093        }
17094
17095        @Override
17096        String getResourcePath() {
17097            return resourcePath;
17098        }
17099
17100        int doPreInstall(int status) {
17101            if (status != PackageManager.INSTALL_SUCCEEDED) {
17102                // Destroy container
17103                PackageHelper.destroySdDir(cid);
17104            } else {
17105                boolean mounted = PackageHelper.isContainerMounted(cid);
17106                if (!mounted) {
17107                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17108                            Process.SYSTEM_UID);
17109                    if (newMountPath != null) {
17110                        setMountPath(newMountPath);
17111                    } else {
17112                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17113                    }
17114                }
17115            }
17116            return status;
17117        }
17118
17119        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17120            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17121            String newMountPath = null;
17122            if (PackageHelper.isContainerMounted(cid)) {
17123                // Unmount the container
17124                if (!PackageHelper.unMountSdDir(cid)) {
17125                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17126                    return false;
17127                }
17128            }
17129            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17130                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17131                        " which might be stale. Will try to clean up.");
17132                // Clean up the stale container and proceed to recreate.
17133                if (!PackageHelper.destroySdDir(newCacheId)) {
17134                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17135                    return false;
17136                }
17137                // Successfully cleaned up stale container. Try to rename again.
17138                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17139                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17140                            + " inspite of cleaning it up.");
17141                    return false;
17142                }
17143            }
17144            if (!PackageHelper.isContainerMounted(newCacheId)) {
17145                Slog.w(TAG, "Mounting container " + newCacheId);
17146                newMountPath = PackageHelper.mountSdDir(newCacheId,
17147                        getEncryptKey(), Process.SYSTEM_UID);
17148            } else {
17149                newMountPath = PackageHelper.getSdDir(newCacheId);
17150            }
17151            if (newMountPath == null) {
17152                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17153                return false;
17154            }
17155            Log.i(TAG, "Succesfully renamed " + cid +
17156                    " to " + newCacheId +
17157                    " at new path: " + newMountPath);
17158            cid = newCacheId;
17159
17160            final File beforeCodeFile = new File(packagePath);
17161            setMountPath(newMountPath);
17162            final File afterCodeFile = new File(packagePath);
17163
17164            // Reflect the rename in scanned details
17165            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17166            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17167                    afterCodeFile, pkg.baseCodePath));
17168            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17169                    afterCodeFile, pkg.splitCodePaths));
17170
17171            // Reflect the rename in app info
17172            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17173            pkg.setApplicationInfoCodePath(pkg.codePath);
17174            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17175            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17176            pkg.setApplicationInfoResourcePath(pkg.codePath);
17177            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17178            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17179
17180            return true;
17181        }
17182
17183        private void setMountPath(String mountPath) {
17184            final File mountFile = new File(mountPath);
17185
17186            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17187            if (monolithicFile.exists()) {
17188                packagePath = monolithicFile.getAbsolutePath();
17189                if (isFwdLocked()) {
17190                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17191                } else {
17192                    resourcePath = packagePath;
17193                }
17194            } else {
17195                packagePath = mountFile.getAbsolutePath();
17196                resourcePath = packagePath;
17197            }
17198        }
17199
17200        int doPostInstall(int status, int uid) {
17201            if (status != PackageManager.INSTALL_SUCCEEDED) {
17202                cleanUp();
17203            } else {
17204                final int groupOwner;
17205                final String protectedFile;
17206                if (isFwdLocked()) {
17207                    groupOwner = UserHandle.getSharedAppGid(uid);
17208                    protectedFile = RES_FILE_NAME;
17209                } else {
17210                    groupOwner = -1;
17211                    protectedFile = null;
17212                }
17213
17214                if (uid < Process.FIRST_APPLICATION_UID
17215                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17216                    Slog.e(TAG, "Failed to finalize " + cid);
17217                    PackageHelper.destroySdDir(cid);
17218                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17219                }
17220
17221                boolean mounted = PackageHelper.isContainerMounted(cid);
17222                if (!mounted) {
17223                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17224                }
17225            }
17226            return status;
17227        }
17228
17229        private void cleanUp() {
17230            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17231
17232            // Destroy secure container
17233            PackageHelper.destroySdDir(cid);
17234        }
17235
17236        private List<String> getAllCodePaths() {
17237            final File codeFile = new File(getCodePath());
17238            if (codeFile != null && codeFile.exists()) {
17239                try {
17240                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17241                    return pkg.getAllCodePaths();
17242                } catch (PackageParserException e) {
17243                    // Ignored; we tried our best
17244                }
17245            }
17246            return Collections.EMPTY_LIST;
17247        }
17248
17249        void cleanUpResourcesLI() {
17250            // Enumerate all code paths before deleting
17251            cleanUpResourcesLI(getAllCodePaths());
17252        }
17253
17254        private void cleanUpResourcesLI(List<String> allCodePaths) {
17255            cleanUp();
17256            removeDexFiles(allCodePaths, instructionSets);
17257        }
17258
17259        String getPackageName() {
17260            return getAsecPackageName(cid);
17261        }
17262
17263        boolean doPostDeleteLI(boolean delete) {
17264            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17265            final List<String> allCodePaths = getAllCodePaths();
17266            boolean mounted = PackageHelper.isContainerMounted(cid);
17267            if (mounted) {
17268                // Unmount first
17269                if (PackageHelper.unMountSdDir(cid)) {
17270                    mounted = false;
17271                }
17272            }
17273            if (!mounted && delete) {
17274                cleanUpResourcesLI(allCodePaths);
17275            }
17276            return !mounted;
17277        }
17278
17279        @Override
17280        int doPreCopy() {
17281            if (isFwdLocked()) {
17282                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17283                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17284                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17285                }
17286            }
17287
17288            return PackageManager.INSTALL_SUCCEEDED;
17289        }
17290
17291        @Override
17292        int doPostCopy(int uid) {
17293            if (isFwdLocked()) {
17294                if (uid < Process.FIRST_APPLICATION_UID
17295                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17296                                RES_FILE_NAME)) {
17297                    Slog.e(TAG, "Failed to finalize " + cid);
17298                    PackageHelper.destroySdDir(cid);
17299                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17300                }
17301            }
17302
17303            return PackageManager.INSTALL_SUCCEEDED;
17304        }
17305    }
17306
17307    /**
17308     * Logic to handle movement of existing installed applications.
17309     */
17310    class MoveInstallArgs extends InstallArgs {
17311        private File codeFile;
17312        private File resourceFile;
17313
17314        /** New install */
17315        MoveInstallArgs(InstallParams params) {
17316            super(params.origin, params.move, params.observer, params.installFlags,
17317                    params.installerPackageName, params.volumeUuid,
17318                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17319                    params.grantedRuntimePermissions,
17320                    params.traceMethod, params.traceCookie, params.certificates,
17321                    params.installReason);
17322        }
17323
17324        int copyApk(IMediaContainerService imcs, boolean temp) {
17325            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17326                    + move.fromUuid + " to " + move.toUuid);
17327            synchronized (mInstaller) {
17328                try {
17329                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17330                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17331                } catch (InstallerException e) {
17332                    Slog.w(TAG, "Failed to move app", e);
17333                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17334                }
17335            }
17336
17337            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17338            resourceFile = codeFile;
17339            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17340
17341            return PackageManager.INSTALL_SUCCEEDED;
17342        }
17343
17344        int doPreInstall(int status) {
17345            if (status != PackageManager.INSTALL_SUCCEEDED) {
17346                cleanUp(move.toUuid);
17347            }
17348            return status;
17349        }
17350
17351        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17352            if (status != PackageManager.INSTALL_SUCCEEDED) {
17353                cleanUp(move.toUuid);
17354                return false;
17355            }
17356
17357            // Reflect the move in app info
17358            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17359            pkg.setApplicationInfoCodePath(pkg.codePath);
17360            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17361            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17362            pkg.setApplicationInfoResourcePath(pkg.codePath);
17363            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17364            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17365
17366            return true;
17367        }
17368
17369        int doPostInstall(int status, int uid) {
17370            if (status == PackageManager.INSTALL_SUCCEEDED) {
17371                cleanUp(move.fromUuid);
17372            } else {
17373                cleanUp(move.toUuid);
17374            }
17375            return status;
17376        }
17377
17378        @Override
17379        String getCodePath() {
17380            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17381        }
17382
17383        @Override
17384        String getResourcePath() {
17385            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17386        }
17387
17388        private boolean cleanUp(String volumeUuid) {
17389            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17390                    move.dataAppName);
17391            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17392            final int[] userIds = sUserManager.getUserIds();
17393            synchronized (mInstallLock) {
17394                // Clean up both app data and code
17395                // All package moves are frozen until finished
17396                for (int userId : userIds) {
17397                    try {
17398                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17399                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17400                    } catch (InstallerException e) {
17401                        Slog.w(TAG, String.valueOf(e));
17402                    }
17403                }
17404                removeCodePathLI(codeFile);
17405            }
17406            return true;
17407        }
17408
17409        void cleanUpResourcesLI() {
17410            throw new UnsupportedOperationException();
17411        }
17412
17413        boolean doPostDeleteLI(boolean delete) {
17414            throw new UnsupportedOperationException();
17415        }
17416    }
17417
17418    static String getAsecPackageName(String packageCid) {
17419        int idx = packageCid.lastIndexOf("-");
17420        if (idx == -1) {
17421            return packageCid;
17422        }
17423        return packageCid.substring(0, idx);
17424    }
17425
17426    // Utility method used to create code paths based on package name and available index.
17427    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17428        String idxStr = "";
17429        int idx = 1;
17430        // Fall back to default value of idx=1 if prefix is not
17431        // part of oldCodePath
17432        if (oldCodePath != null) {
17433            String subStr = oldCodePath;
17434            // Drop the suffix right away
17435            if (suffix != null && subStr.endsWith(suffix)) {
17436                subStr = subStr.substring(0, subStr.length() - suffix.length());
17437            }
17438            // If oldCodePath already contains prefix find out the
17439            // ending index to either increment or decrement.
17440            int sidx = subStr.lastIndexOf(prefix);
17441            if (sidx != -1) {
17442                subStr = subStr.substring(sidx + prefix.length());
17443                if (subStr != null) {
17444                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17445                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17446                    }
17447                    try {
17448                        idx = Integer.parseInt(subStr);
17449                        if (idx <= 1) {
17450                            idx++;
17451                        } else {
17452                            idx--;
17453                        }
17454                    } catch(NumberFormatException e) {
17455                    }
17456                }
17457            }
17458        }
17459        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17460        return prefix + idxStr;
17461    }
17462
17463    private File getNextCodePath(File targetDir, String packageName) {
17464        File result;
17465        SecureRandom random = new SecureRandom();
17466        byte[] bytes = new byte[16];
17467        do {
17468            random.nextBytes(bytes);
17469            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17470            result = new File(targetDir, packageName + "-" + suffix);
17471        } while (result.exists());
17472        return result;
17473    }
17474
17475    // Utility method that returns the relative package path with respect
17476    // to the installation directory. Like say for /data/data/com.test-1.apk
17477    // string com.test-1 is returned.
17478    static String deriveCodePathName(String codePath) {
17479        if (codePath == null) {
17480            return null;
17481        }
17482        final File codeFile = new File(codePath);
17483        final String name = codeFile.getName();
17484        if (codeFile.isDirectory()) {
17485            return name;
17486        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17487            final int lastDot = name.lastIndexOf('.');
17488            return name.substring(0, lastDot);
17489        } else {
17490            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17491            return null;
17492        }
17493    }
17494
17495    static class PackageInstalledInfo {
17496        String name;
17497        int uid;
17498        // The set of users that originally had this package installed.
17499        int[] origUsers;
17500        // The set of users that now have this package installed.
17501        int[] newUsers;
17502        PackageParser.Package pkg;
17503        int returnCode;
17504        String returnMsg;
17505        String installerPackageName;
17506        PackageRemovedInfo removedInfo;
17507        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17508
17509        public void setError(int code, String msg) {
17510            setReturnCode(code);
17511            setReturnMessage(msg);
17512            Slog.w(TAG, msg);
17513        }
17514
17515        public void setError(String msg, PackageParserException e) {
17516            setReturnCode(e.error);
17517            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17518            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17519            for (int i = 0; i < childCount; i++) {
17520                addedChildPackages.valueAt(i).setError(msg, e);
17521            }
17522            Slog.w(TAG, msg, e);
17523        }
17524
17525        public void setError(String msg, PackageManagerException e) {
17526            returnCode = 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 setReturnCode(int returnCode) {
17536            this.returnCode = returnCode;
17537            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17538            for (int i = 0; i < childCount; i++) {
17539                addedChildPackages.valueAt(i).returnCode = returnCode;
17540            }
17541        }
17542
17543        private void setReturnMessage(String returnMsg) {
17544            this.returnMsg = returnMsg;
17545            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17546            for (int i = 0; i < childCount; i++) {
17547                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17548            }
17549        }
17550
17551        // In some error cases we want to convey more info back to the observer
17552        String origPackage;
17553        String origPermission;
17554    }
17555
17556    /*
17557     * Install a non-existing package.
17558     */
17559    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17560            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17561            PackageInstalledInfo res, int installReason) {
17562        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17563
17564        // Remember this for later, in case we need to rollback this install
17565        String pkgName = pkg.packageName;
17566
17567        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17568
17569        synchronized(mPackages) {
17570            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17571            if (renamedPackage != null) {
17572                // A package with the same name is already installed, though
17573                // it has been renamed to an older name.  The package we
17574                // are trying to install should be installed as an update to
17575                // the existing one, but that has not been requested, so bail.
17576                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17577                        + " without first uninstalling package running as "
17578                        + renamedPackage);
17579                return;
17580            }
17581            if (mPackages.containsKey(pkgName)) {
17582                // Don't allow installation over an existing package with the same name.
17583                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17584                        + " without first uninstalling.");
17585                return;
17586            }
17587        }
17588
17589        try {
17590            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17591                    System.currentTimeMillis(), user);
17592
17593            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17594
17595            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17596                prepareAppDataAfterInstallLIF(newPackage);
17597
17598            } else {
17599                // Remove package from internal structures, but keep around any
17600                // data that might have already existed
17601                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17602                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17603            }
17604        } catch (PackageManagerException e) {
17605            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17606        }
17607
17608        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17609    }
17610
17611    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17612        // Can't rotate keys during boot or if sharedUser.
17613        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17614                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17615            return false;
17616        }
17617        // app is using upgradeKeySets; make sure all are valid
17618        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17619        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17620        for (int i = 0; i < upgradeKeySets.length; i++) {
17621            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17622                Slog.wtf(TAG, "Package "
17623                         + (oldPs.name != null ? oldPs.name : "<null>")
17624                         + " contains upgrade-key-set reference to unknown key-set: "
17625                         + upgradeKeySets[i]
17626                         + " reverting to signatures check.");
17627                return false;
17628            }
17629        }
17630        return true;
17631    }
17632
17633    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17634        // Upgrade keysets are being used.  Determine if new package has a superset of the
17635        // required keys.
17636        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17637        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17638        for (int i = 0; i < upgradeKeySets.length; i++) {
17639            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17640            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17641                return true;
17642            }
17643        }
17644        return false;
17645    }
17646
17647    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17648        try (DigestInputStream digestStream =
17649                new DigestInputStream(new FileInputStream(file), digest)) {
17650            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17651        }
17652    }
17653
17654    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17655            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17656            int installReason) {
17657        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17658
17659        final PackageParser.Package oldPackage;
17660        final PackageSetting ps;
17661        final String pkgName = pkg.packageName;
17662        final int[] allUsers;
17663        final int[] installedUsers;
17664
17665        synchronized(mPackages) {
17666            oldPackage = mPackages.get(pkgName);
17667            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17668
17669            // don't allow upgrade to target a release SDK from a pre-release SDK
17670            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17671                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17672            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17673                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17674            if (oldTargetsPreRelease
17675                    && !newTargetsPreRelease
17676                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17677                Slog.w(TAG, "Can't install package targeting released sdk");
17678                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17679                return;
17680            }
17681
17682            ps = mSettings.mPackages.get(pkgName);
17683
17684            // verify signatures are valid
17685            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17686                if (!checkUpgradeKeySetLP(ps, pkg)) {
17687                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17688                            "New package not signed by keys specified by upgrade-keysets: "
17689                                    + pkgName);
17690                    return;
17691                }
17692            } else {
17693                // default to original signature matching
17694                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17695                        != PackageManager.SIGNATURE_MATCH) {
17696                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17697                            "New package has a different signature: " + pkgName);
17698                    return;
17699                }
17700            }
17701
17702            // don't allow a system upgrade unless the upgrade hash matches
17703            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17704                byte[] digestBytes = null;
17705                try {
17706                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17707                    updateDigest(digest, new File(pkg.baseCodePath));
17708                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17709                        for (String path : pkg.splitCodePaths) {
17710                            updateDigest(digest, new File(path));
17711                        }
17712                    }
17713                    digestBytes = digest.digest();
17714                } catch (NoSuchAlgorithmException | IOException e) {
17715                    res.setError(INSTALL_FAILED_INVALID_APK,
17716                            "Could not compute hash: " + pkgName);
17717                    return;
17718                }
17719                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17720                    res.setError(INSTALL_FAILED_INVALID_APK,
17721                            "New package fails restrict-update check: " + pkgName);
17722                    return;
17723                }
17724                // retain upgrade restriction
17725                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17726            }
17727
17728            // Check for shared user id changes
17729            String invalidPackageName =
17730                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17731            if (invalidPackageName != null) {
17732                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17733                        "Package " + invalidPackageName + " tried to change user "
17734                                + oldPackage.mSharedUserId);
17735                return;
17736            }
17737
17738            // check if the new package supports all of the abis which the old package supports
17739            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
17740            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
17741            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
17742                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17743                        "Update to package " + pkgName + " doesn't support multi arch");
17744                return;
17745            }
17746
17747            // In case of rollback, remember per-user/profile install state
17748            allUsers = sUserManager.getUserIds();
17749            installedUsers = ps.queryInstalledUsers(allUsers, true);
17750
17751            // don't allow an upgrade from full to ephemeral
17752            if (isInstantApp) {
17753                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17754                    for (int currentUser : allUsers) {
17755                        if (!ps.getInstantApp(currentUser)) {
17756                            // can't downgrade from full to instant
17757                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17758                                    + " for user: " + currentUser);
17759                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17760                            return;
17761                        }
17762                    }
17763                } else if (!ps.getInstantApp(user.getIdentifier())) {
17764                    // can't downgrade from full to instant
17765                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17766                            + " for user: " + user.getIdentifier());
17767                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17768                    return;
17769                }
17770            }
17771        }
17772
17773        // Update what is removed
17774        res.removedInfo = new PackageRemovedInfo(this);
17775        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17776        res.removedInfo.removedPackage = oldPackage.packageName;
17777        res.removedInfo.installerPackageName = ps.installerPackageName;
17778        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17779        res.removedInfo.isUpdate = true;
17780        res.removedInfo.origUsers = installedUsers;
17781        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17782        for (int i = 0; i < installedUsers.length; i++) {
17783            final int userId = installedUsers[i];
17784            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17785        }
17786
17787        final int childCount = (oldPackage.childPackages != null)
17788                ? oldPackage.childPackages.size() : 0;
17789        for (int i = 0; i < childCount; i++) {
17790            boolean childPackageUpdated = false;
17791            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17792            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17793            if (res.addedChildPackages != null) {
17794                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17795                if (childRes != null) {
17796                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17797                    childRes.removedInfo.removedPackage = childPkg.packageName;
17798                    if (childPs != null) {
17799                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17800                    }
17801                    childRes.removedInfo.isUpdate = true;
17802                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17803                    childPackageUpdated = true;
17804                }
17805            }
17806            if (!childPackageUpdated) {
17807                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17808                childRemovedRes.removedPackage = childPkg.packageName;
17809                if (childPs != null) {
17810                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17811                }
17812                childRemovedRes.isUpdate = false;
17813                childRemovedRes.dataRemoved = true;
17814                synchronized (mPackages) {
17815                    if (childPs != null) {
17816                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17817                    }
17818                }
17819                if (res.removedInfo.removedChildPackages == null) {
17820                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17821                }
17822                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17823            }
17824        }
17825
17826        boolean sysPkg = (isSystemApp(oldPackage));
17827        if (sysPkg) {
17828            // Set the system/privileged flags as needed
17829            final boolean privileged =
17830                    (oldPackage.applicationInfo.privateFlags
17831                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17832            final int systemPolicyFlags = policyFlags
17833                    | PackageParser.PARSE_IS_SYSTEM
17834                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17835
17836            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17837                    user, allUsers, installerPackageName, res, installReason);
17838        } else {
17839            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17840                    user, allUsers, installerPackageName, res, installReason);
17841        }
17842    }
17843
17844    @Override
17845    public List<String> getPreviousCodePaths(String packageName) {
17846        final int callingUid = Binder.getCallingUid();
17847        final List<String> result = new ArrayList<>();
17848        if (getInstantAppPackageName(callingUid) != null) {
17849            return result;
17850        }
17851        final PackageSetting ps = mSettings.mPackages.get(packageName);
17852        if (ps != null
17853                && ps.oldCodePaths != null
17854                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17855            result.addAll(ps.oldCodePaths);
17856        }
17857        return result;
17858    }
17859
17860    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17861            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17862            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17863            int installReason) {
17864        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17865                + deletedPackage);
17866
17867        String pkgName = deletedPackage.packageName;
17868        boolean deletedPkg = true;
17869        boolean addedPkg = false;
17870        boolean updatedSettings = false;
17871        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17872        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17873                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17874
17875        final long origUpdateTime = (pkg.mExtras != null)
17876                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17877
17878        // First delete the existing package while retaining the data directory
17879        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17880                res.removedInfo, true, pkg)) {
17881            // If the existing package wasn't successfully deleted
17882            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17883            deletedPkg = false;
17884        } else {
17885            // Successfully deleted the old package; proceed with replace.
17886
17887            // If deleted package lived in a container, give users a chance to
17888            // relinquish resources before killing.
17889            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17890                if (DEBUG_INSTALL) {
17891                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17892                }
17893                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17894                final ArrayList<String> pkgList = new ArrayList<String>(1);
17895                pkgList.add(deletedPackage.applicationInfo.packageName);
17896                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17897            }
17898
17899            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17900                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17901
17902            try {
17903                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17904                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17905                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17906                        installReason);
17907
17908                // Update the in-memory copy of the previous code paths.
17909                PackageSetting ps = mSettings.mPackages.get(pkgName);
17910                if (!killApp) {
17911                    if (ps.oldCodePaths == null) {
17912                        ps.oldCodePaths = new ArraySet<>();
17913                    }
17914                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17915                    if (deletedPackage.splitCodePaths != null) {
17916                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17917                    }
17918                } else {
17919                    ps.oldCodePaths = null;
17920                }
17921                if (ps.childPackageNames != null) {
17922                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17923                        final String childPkgName = ps.childPackageNames.get(i);
17924                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17925                        childPs.oldCodePaths = ps.oldCodePaths;
17926                    }
17927                }
17928                // set instant app status, but, only if it's explicitly specified
17929                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17930                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17931                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17932                prepareAppDataAfterInstallLIF(newPackage);
17933                addedPkg = true;
17934                mDexManager.notifyPackageUpdated(newPackage.packageName,
17935                        newPackage.baseCodePath, newPackage.splitCodePaths);
17936            } catch (PackageManagerException e) {
17937                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17938            }
17939        }
17940
17941        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17942            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17943
17944            // Revert all internal state mutations and added folders for the failed install
17945            if (addedPkg) {
17946                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17947                        res.removedInfo, true, null);
17948            }
17949
17950            // Restore the old package
17951            if (deletedPkg) {
17952                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17953                File restoreFile = new File(deletedPackage.codePath);
17954                // Parse old package
17955                boolean oldExternal = isExternal(deletedPackage);
17956                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17957                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17958                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17959                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17960                try {
17961                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17962                            null);
17963                } catch (PackageManagerException e) {
17964                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17965                            + e.getMessage());
17966                    return;
17967                }
17968
17969                synchronized (mPackages) {
17970                    // Ensure the installer package name up to date
17971                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17972
17973                    // Update permissions for restored package
17974                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17975
17976                    mSettings.writeLPr();
17977                }
17978
17979                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17980            }
17981        } else {
17982            synchronized (mPackages) {
17983                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17984                if (ps != null) {
17985                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17986                    if (res.removedInfo.removedChildPackages != null) {
17987                        final int childCount = res.removedInfo.removedChildPackages.size();
17988                        // Iterate in reverse as we may modify the collection
17989                        for (int i = childCount - 1; i >= 0; i--) {
17990                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17991                            if (res.addedChildPackages.containsKey(childPackageName)) {
17992                                res.removedInfo.removedChildPackages.removeAt(i);
17993                            } else {
17994                                PackageRemovedInfo childInfo = res.removedInfo
17995                                        .removedChildPackages.valueAt(i);
17996                                childInfo.removedForAllUsers = mPackages.get(
17997                                        childInfo.removedPackage) == null;
17998                            }
17999                        }
18000                    }
18001                }
18002            }
18003        }
18004    }
18005
18006    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
18007            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
18008            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
18009            int installReason) {
18010        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
18011                + ", old=" + deletedPackage);
18012
18013        final boolean disabledSystem;
18014
18015        // Remove existing system package
18016        removePackageLI(deletedPackage, true);
18017
18018        synchronized (mPackages) {
18019            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
18020        }
18021        if (!disabledSystem) {
18022            // We didn't need to disable the .apk as a current system package,
18023            // which means we are replacing another update that is already
18024            // installed.  We need to make sure to delete the older one's .apk.
18025            res.removedInfo.args = createInstallArgsForExisting(0,
18026                    deletedPackage.applicationInfo.getCodePath(),
18027                    deletedPackage.applicationInfo.getResourcePath(),
18028                    getAppDexInstructionSets(deletedPackage.applicationInfo));
18029        } else {
18030            res.removedInfo.args = null;
18031        }
18032
18033        // Successfully disabled the old package. Now proceed with re-installation
18034        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
18035                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18036
18037        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18038        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
18039                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
18040
18041        PackageParser.Package newPackage = null;
18042        try {
18043            // Add the package to the internal data structures
18044            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
18045
18046            // Set the update and install times
18047            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
18048            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
18049                    System.currentTimeMillis());
18050
18051            // Update the package dynamic state if succeeded
18052            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18053                // Now that the install succeeded make sure we remove data
18054                // directories for any child package the update removed.
18055                final int deletedChildCount = (deletedPackage.childPackages != null)
18056                        ? deletedPackage.childPackages.size() : 0;
18057                final int newChildCount = (newPackage.childPackages != null)
18058                        ? newPackage.childPackages.size() : 0;
18059                for (int i = 0; i < deletedChildCount; i++) {
18060                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
18061                    boolean childPackageDeleted = true;
18062                    for (int j = 0; j < newChildCount; j++) {
18063                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
18064                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
18065                            childPackageDeleted = false;
18066                            break;
18067                        }
18068                    }
18069                    if (childPackageDeleted) {
18070                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
18071                                deletedChildPkg.packageName);
18072                        if (ps != null && res.removedInfo.removedChildPackages != null) {
18073                            PackageRemovedInfo removedChildRes = res.removedInfo
18074                                    .removedChildPackages.get(deletedChildPkg.packageName);
18075                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
18076                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
18077                        }
18078                    }
18079                }
18080
18081                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
18082                        installReason);
18083                prepareAppDataAfterInstallLIF(newPackage);
18084
18085                mDexManager.notifyPackageUpdated(newPackage.packageName,
18086                            newPackage.baseCodePath, newPackage.splitCodePaths);
18087            }
18088        } catch (PackageManagerException e) {
18089            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
18090            res.setError("Package couldn't be installed in " + pkg.codePath, e);
18091        }
18092
18093        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
18094            // Re installation failed. Restore old information
18095            // Remove new pkg information
18096            if (newPackage != null) {
18097                removeInstalledPackageLI(newPackage, true);
18098            }
18099            // Add back the old system package
18100            try {
18101                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
18102            } catch (PackageManagerException e) {
18103                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
18104            }
18105
18106            synchronized (mPackages) {
18107                if (disabledSystem) {
18108                    enableSystemPackageLPw(deletedPackage);
18109                }
18110
18111                // Ensure the installer package name up to date
18112                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18113
18114                // Update permissions for restored package
18115                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18116
18117                mSettings.writeLPr();
18118            }
18119
18120            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18121                    + " after failed upgrade");
18122        }
18123    }
18124
18125    /**
18126     * Checks whether the parent or any of the child packages have a change shared
18127     * user. For a package to be a valid update the shred users of the parent and
18128     * the children should match. We may later support changing child shared users.
18129     * @param oldPkg The updated package.
18130     * @param newPkg The update package.
18131     * @return The shared user that change between the versions.
18132     */
18133    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18134            PackageParser.Package newPkg) {
18135        // Check parent shared user
18136        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18137            return newPkg.packageName;
18138        }
18139        // Check child shared users
18140        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18141        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18142        for (int i = 0; i < newChildCount; i++) {
18143            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18144            // If this child was present, did it have the same shared user?
18145            for (int j = 0; j < oldChildCount; j++) {
18146                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18147                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18148                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18149                    return newChildPkg.packageName;
18150                }
18151            }
18152        }
18153        return null;
18154    }
18155
18156    private void removeNativeBinariesLI(PackageSetting ps) {
18157        // Remove the lib path for the parent package
18158        if (ps != null) {
18159            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18160            // Remove the lib path for the child packages
18161            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18162            for (int i = 0; i < childCount; i++) {
18163                PackageSetting childPs = null;
18164                synchronized (mPackages) {
18165                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18166                }
18167                if (childPs != null) {
18168                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18169                            .legacyNativeLibraryPathString);
18170                }
18171            }
18172        }
18173    }
18174
18175    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18176        // Enable the parent package
18177        mSettings.enableSystemPackageLPw(pkg.packageName);
18178        // Enable the child packages
18179        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18180        for (int i = 0; i < childCount; i++) {
18181            PackageParser.Package childPkg = pkg.childPackages.get(i);
18182            mSettings.enableSystemPackageLPw(childPkg.packageName);
18183        }
18184    }
18185
18186    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18187            PackageParser.Package newPkg) {
18188        // Disable the parent package (parent always replaced)
18189        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18190        // Disable the child packages
18191        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18192        for (int i = 0; i < childCount; i++) {
18193            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18194            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18195            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18196        }
18197        return disabled;
18198    }
18199
18200    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18201            String installerPackageName) {
18202        // Enable the parent package
18203        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18204        // Enable the child packages
18205        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18206        for (int i = 0; i < childCount; i++) {
18207            PackageParser.Package childPkg = pkg.childPackages.get(i);
18208            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18209        }
18210    }
18211
18212    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18213        // Collect all used permissions in the UID
18214        ArraySet<String> usedPermissions = new ArraySet<>();
18215        final int packageCount = su.packages.size();
18216        for (int i = 0; i < packageCount; i++) {
18217            PackageSetting ps = su.packages.valueAt(i);
18218            if (ps.pkg == null) {
18219                continue;
18220            }
18221            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18222            for (int j = 0; j < requestedPermCount; j++) {
18223                String permission = ps.pkg.requestedPermissions.get(j);
18224                BasePermission bp = mSettings.mPermissions.get(permission);
18225                if (bp != null) {
18226                    usedPermissions.add(permission);
18227                }
18228            }
18229        }
18230
18231        PermissionsState permissionsState = su.getPermissionsState();
18232        // Prune install permissions
18233        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18234        final int installPermCount = installPermStates.size();
18235        for (int i = installPermCount - 1; i >= 0;  i--) {
18236            PermissionState permissionState = installPermStates.get(i);
18237            if (!usedPermissions.contains(permissionState.getName())) {
18238                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18239                if (bp != null) {
18240                    permissionsState.revokeInstallPermission(bp);
18241                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18242                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18243                }
18244            }
18245        }
18246
18247        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18248
18249        // Prune runtime permissions
18250        for (int userId : allUserIds) {
18251            List<PermissionState> runtimePermStates = permissionsState
18252                    .getRuntimePermissionStates(userId);
18253            final int runtimePermCount = runtimePermStates.size();
18254            for (int i = runtimePermCount - 1; i >= 0; i--) {
18255                PermissionState permissionState = runtimePermStates.get(i);
18256                if (!usedPermissions.contains(permissionState.getName())) {
18257                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18258                    if (bp != null) {
18259                        permissionsState.revokeRuntimePermission(bp, userId);
18260                        permissionsState.updatePermissionFlags(bp, userId,
18261                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18262                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18263                                runtimePermissionChangedUserIds, userId);
18264                    }
18265                }
18266            }
18267        }
18268
18269        return runtimePermissionChangedUserIds;
18270    }
18271
18272    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18273            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18274        // Update the parent package setting
18275        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18276                res, user, installReason);
18277        // Update the child packages setting
18278        final int childCount = (newPackage.childPackages != null)
18279                ? newPackage.childPackages.size() : 0;
18280        for (int i = 0; i < childCount; i++) {
18281            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18282            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18283            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18284                    childRes.origUsers, childRes, user, installReason);
18285        }
18286    }
18287
18288    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18289            String installerPackageName, int[] allUsers, int[] installedForUsers,
18290            PackageInstalledInfo res, UserHandle user, int installReason) {
18291        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18292
18293        String pkgName = newPackage.packageName;
18294        synchronized (mPackages) {
18295            //write settings. the installStatus will be incomplete at this stage.
18296            //note that the new package setting would have already been
18297            //added to mPackages. It hasn't been persisted yet.
18298            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18299            // TODO: Remove this write? It's also written at the end of this method
18300            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18301            mSettings.writeLPr();
18302            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18303        }
18304
18305        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18306        synchronized (mPackages) {
18307            updatePermissionsLPw(newPackage.packageName, newPackage,
18308                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18309                            ? UPDATE_PERMISSIONS_ALL : 0));
18310            // For system-bundled packages, we assume that installing an upgraded version
18311            // of the package implies that the user actually wants to run that new code,
18312            // so we enable the package.
18313            PackageSetting ps = mSettings.mPackages.get(pkgName);
18314            final int userId = user.getIdentifier();
18315            if (ps != null) {
18316                if (isSystemApp(newPackage)) {
18317                    if (DEBUG_INSTALL) {
18318                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18319                    }
18320                    // Enable system package for requested users
18321                    if (res.origUsers != null) {
18322                        for (int origUserId : res.origUsers) {
18323                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18324                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18325                                        origUserId, installerPackageName);
18326                            }
18327                        }
18328                    }
18329                    // Also convey the prior install/uninstall state
18330                    if (allUsers != null && installedForUsers != null) {
18331                        for (int currentUserId : allUsers) {
18332                            final boolean installed = ArrayUtils.contains(
18333                                    installedForUsers, currentUserId);
18334                            if (DEBUG_INSTALL) {
18335                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18336                            }
18337                            ps.setInstalled(installed, currentUserId);
18338                        }
18339                        // these install state changes will be persisted in the
18340                        // upcoming call to mSettings.writeLPr().
18341                    }
18342                }
18343                // It's implied that when a user requests installation, they want the app to be
18344                // installed and enabled.
18345                if (userId != UserHandle.USER_ALL) {
18346                    ps.setInstalled(true, userId);
18347                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18348                }
18349
18350                // When replacing an existing package, preserve the original install reason for all
18351                // users that had the package installed before.
18352                final Set<Integer> previousUserIds = new ArraySet<>();
18353                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18354                    final int installReasonCount = res.removedInfo.installReasons.size();
18355                    for (int i = 0; i < installReasonCount; i++) {
18356                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18357                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18358                        ps.setInstallReason(previousInstallReason, previousUserId);
18359                        previousUserIds.add(previousUserId);
18360                    }
18361                }
18362
18363                // Set install reason for users that are having the package newly installed.
18364                if (userId == UserHandle.USER_ALL) {
18365                    for (int currentUserId : sUserManager.getUserIds()) {
18366                        if (!previousUserIds.contains(currentUserId)) {
18367                            ps.setInstallReason(installReason, currentUserId);
18368                        }
18369                    }
18370                } else if (!previousUserIds.contains(userId)) {
18371                    ps.setInstallReason(installReason, userId);
18372                }
18373                mSettings.writeKernelMappingLPr(ps);
18374            }
18375            res.name = pkgName;
18376            res.uid = newPackage.applicationInfo.uid;
18377            res.pkg = newPackage;
18378            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18379            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18380            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18381            //to update install status
18382            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18383            mSettings.writeLPr();
18384            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18385        }
18386
18387        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18388    }
18389
18390    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18391        try {
18392            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18393            installPackageLI(args, res);
18394        } finally {
18395            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18396        }
18397    }
18398
18399    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18400        final int installFlags = args.installFlags;
18401        final String installerPackageName = args.installerPackageName;
18402        final String volumeUuid = args.volumeUuid;
18403        final File tmpPackageFile = new File(args.getCodePath());
18404        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18405        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18406                || (args.volumeUuid != null));
18407        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18408        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18409        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18410        final boolean virtualPreload =
18411                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18412        boolean replace = false;
18413        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18414        if (args.move != null) {
18415            // moving a complete application; perform an initial scan on the new install location
18416            scanFlags |= SCAN_INITIAL;
18417        }
18418        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18419            scanFlags |= SCAN_DONT_KILL_APP;
18420        }
18421        if (instantApp) {
18422            scanFlags |= SCAN_AS_INSTANT_APP;
18423        }
18424        if (fullApp) {
18425            scanFlags |= SCAN_AS_FULL_APP;
18426        }
18427        if (virtualPreload) {
18428            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18429        }
18430
18431        // Result object to be returned
18432        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18433        res.installerPackageName = installerPackageName;
18434
18435        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18436
18437        // Sanity check
18438        if (instantApp && (forwardLocked || onExternal)) {
18439            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18440                    + " external=" + onExternal);
18441            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18442            return;
18443        }
18444
18445        // Retrieve PackageSettings and parse package
18446        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18447                | PackageParser.PARSE_ENFORCE_CODE
18448                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18449                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18450                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18451                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18452        PackageParser pp = new PackageParser();
18453        pp.setSeparateProcesses(mSeparateProcesses);
18454        pp.setDisplayMetrics(mMetrics);
18455        pp.setCallback(mPackageParserCallback);
18456
18457        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18458        final PackageParser.Package pkg;
18459        try {
18460            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18461            DexMetadataHelper.validatePackageDexMetadata(pkg);
18462        } catch (PackageParserException e) {
18463            res.setError("Failed parse during installPackageLI", e);
18464            return;
18465        } finally {
18466            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18467        }
18468
18469        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18470        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18471            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18472            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18473                    "Instant app package must target O");
18474            return;
18475        }
18476        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18477            Slog.w(TAG, "Instant app package " + pkg.packageName
18478                    + " does not target targetSandboxVersion 2");
18479            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18480                    "Instant app package must use targetSanboxVersion 2");
18481            return;
18482        }
18483
18484        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18485            // Static shared libraries have synthetic package names
18486            renameStaticSharedLibraryPackage(pkg);
18487
18488            // No static shared libs on external storage
18489            if (onExternal) {
18490                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18491                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18492                        "Packages declaring static-shared libs cannot be updated");
18493                return;
18494            }
18495        }
18496
18497        // If we are installing a clustered package add results for the children
18498        if (pkg.childPackages != null) {
18499            synchronized (mPackages) {
18500                final int childCount = pkg.childPackages.size();
18501                for (int i = 0; i < childCount; i++) {
18502                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18503                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18504                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18505                    childRes.pkg = childPkg;
18506                    childRes.name = childPkg.packageName;
18507                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18508                    if (childPs != null) {
18509                        childRes.origUsers = childPs.queryInstalledUsers(
18510                                sUserManager.getUserIds(), true);
18511                    }
18512                    if ((mPackages.containsKey(childPkg.packageName))) {
18513                        childRes.removedInfo = new PackageRemovedInfo(this);
18514                        childRes.removedInfo.removedPackage = childPkg.packageName;
18515                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18516                    }
18517                    if (res.addedChildPackages == null) {
18518                        res.addedChildPackages = new ArrayMap<>();
18519                    }
18520                    res.addedChildPackages.put(childPkg.packageName, childRes);
18521                }
18522            }
18523        }
18524
18525        // If package doesn't declare API override, mark that we have an install
18526        // time CPU ABI override.
18527        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18528            pkg.cpuAbiOverride = args.abiOverride;
18529        }
18530
18531        String pkgName = res.name = pkg.packageName;
18532        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18533            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18534                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18535                return;
18536            }
18537        }
18538
18539        try {
18540            // either use what we've been given or parse directly from the APK
18541            if (args.certificates != null) {
18542                try {
18543                    PackageParser.populateCertificates(pkg, args.certificates);
18544                } catch (PackageParserException e) {
18545                    // there was something wrong with the certificates we were given;
18546                    // try to pull them from the APK
18547                    PackageParser.collectCertificates(pkg, parseFlags);
18548                }
18549            } else {
18550                PackageParser.collectCertificates(pkg, parseFlags);
18551            }
18552        } catch (PackageParserException e) {
18553            res.setError("Failed collect during installPackageLI", e);
18554            return;
18555        }
18556
18557        // Get rid of all references to package scan path via parser.
18558        pp = null;
18559        String oldCodePath = null;
18560        boolean systemApp = false;
18561        synchronized (mPackages) {
18562            // Check if installing already existing package
18563            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18564                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18565                if (pkg.mOriginalPackages != null
18566                        && pkg.mOriginalPackages.contains(oldName)
18567                        && mPackages.containsKey(oldName)) {
18568                    // This package is derived from an original package,
18569                    // and this device has been updating from that original
18570                    // name.  We must continue using the original name, so
18571                    // rename the new package here.
18572                    pkg.setPackageName(oldName);
18573                    pkgName = pkg.packageName;
18574                    replace = true;
18575                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18576                            + oldName + " pkgName=" + pkgName);
18577                } else if (mPackages.containsKey(pkgName)) {
18578                    // This package, under its official name, already exists
18579                    // on the device; we should replace it.
18580                    replace = true;
18581                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18582                }
18583
18584                // Child packages are installed through the parent package
18585                if (pkg.parentPackage != null) {
18586                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18587                            "Package " + pkg.packageName + " is child of package "
18588                                    + pkg.parentPackage.parentPackage + ". Child packages "
18589                                    + "can be updated only through the parent package.");
18590                    return;
18591                }
18592
18593                if (replace) {
18594                    // Prevent apps opting out from runtime permissions
18595                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18596                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18597                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18598                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18599                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18600                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18601                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18602                                        + " doesn't support runtime permissions but the old"
18603                                        + " target SDK " + oldTargetSdk + " does.");
18604                        return;
18605                    }
18606                    // Prevent persistent apps from being updated
18607                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
18608                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
18609                                "Package " + oldPackage.packageName + " is a persistent app. "
18610                                        + "Persistent apps are not updateable.");
18611                        return;
18612                    }
18613                    // Prevent apps from downgrading their targetSandbox.
18614                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18615                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18616                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18617                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18618                                "Package " + pkg.packageName + " new target sandbox "
18619                                + newTargetSandbox + " is incompatible with the previous value of"
18620                                + oldTargetSandbox + ".");
18621                        return;
18622                    }
18623
18624                    // Prevent installing of child packages
18625                    if (oldPackage.parentPackage != null) {
18626                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18627                                "Package " + pkg.packageName + " is child of package "
18628                                        + oldPackage.parentPackage + ". Child packages "
18629                                        + "can be updated only through the parent package.");
18630                        return;
18631                    }
18632                }
18633            }
18634
18635            PackageSetting ps = mSettings.mPackages.get(pkgName);
18636            if (ps != null) {
18637                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18638
18639                // Static shared libs have same package with different versions where
18640                // we internally use a synthetic package name to allow multiple versions
18641                // of the same package, therefore we need to compare signatures against
18642                // the package setting for the latest library version.
18643                PackageSetting signatureCheckPs = ps;
18644                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18645                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18646                    if (libraryEntry != null) {
18647                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18648                    }
18649                }
18650
18651                // Quick sanity check that we're signed correctly if updating;
18652                // we'll check this again later when scanning, but we want to
18653                // bail early here before tripping over redefined permissions.
18654                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18655                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18656                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18657                                + pkg.packageName + " upgrade keys do not match the "
18658                                + "previously installed version");
18659                        return;
18660                    }
18661                } else {
18662                    try {
18663                        verifySignaturesLP(signatureCheckPs, pkg);
18664                    } catch (PackageManagerException e) {
18665                        res.setError(e.error, e.getMessage());
18666                        return;
18667                    }
18668                }
18669
18670                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18671                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18672                    systemApp = (ps.pkg.applicationInfo.flags &
18673                            ApplicationInfo.FLAG_SYSTEM) != 0;
18674                }
18675                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18676            }
18677
18678            int N = pkg.permissions.size();
18679            for (int i = N-1; i >= 0; i--) {
18680                PackageParser.Permission perm = pkg.permissions.get(i);
18681                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18682
18683                // Don't allow anyone but the system to define ephemeral permissions.
18684                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18685                        && !systemApp) {
18686                    Slog.w(TAG, "Non-System package " + pkg.packageName
18687                            + " attempting to delcare ephemeral permission "
18688                            + perm.info.name + "; Removing ephemeral.");
18689                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18690                }
18691                // Check whether the newly-scanned package wants to define an already-defined perm
18692                if (bp != null) {
18693                    // If the defining package is signed with our cert, it's okay.  This
18694                    // also includes the "updating the same package" case, of course.
18695                    // "updating same package" could also involve key-rotation.
18696                    final boolean sigsOk;
18697                    if (bp.sourcePackage.equals(pkg.packageName)
18698                            && (bp.packageSetting instanceof PackageSetting)
18699                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18700                                    scanFlags))) {
18701                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18702                    } else {
18703                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18704                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18705                    }
18706                    if (!sigsOk) {
18707                        // If the owning package is the system itself, we log but allow
18708                        // install to proceed; we fail the install on all other permission
18709                        // redefinitions.
18710                        if (!bp.sourcePackage.equals("android")) {
18711                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18712                                    + pkg.packageName + " attempting to redeclare permission "
18713                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18714                            res.origPermission = perm.info.name;
18715                            res.origPackage = bp.sourcePackage;
18716                            return;
18717                        } else {
18718                            Slog.w(TAG, "Package " + pkg.packageName
18719                                    + " attempting to redeclare system permission "
18720                                    + perm.info.name + "; ignoring new declaration");
18721                            pkg.permissions.remove(i);
18722                        }
18723                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18724                        // Prevent apps to change protection level to dangerous from any other
18725                        // type as this would allow a privilege escalation where an app adds a
18726                        // normal/signature permission in other app's group and later redefines
18727                        // it as dangerous leading to the group auto-grant.
18728                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18729                                == PermissionInfo.PROTECTION_DANGEROUS) {
18730                            if (bp != null && !bp.isRuntime()) {
18731                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18732                                        + "non-runtime permission " + perm.info.name
18733                                        + " to runtime; keeping old protection level");
18734                                perm.info.protectionLevel = bp.protectionLevel;
18735                            }
18736                        }
18737                    }
18738                }
18739            }
18740        }
18741
18742        if (systemApp) {
18743            if (onExternal) {
18744                // Abort update; system app can't be replaced with app on sdcard
18745                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18746                        "Cannot install updates to system apps on sdcard");
18747                return;
18748            } else if (instantApp) {
18749                // Abort update; system app can't be replaced with an instant app
18750                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18751                        "Cannot update a system app with an instant app");
18752                return;
18753            }
18754        }
18755
18756        if (args.move != null) {
18757            // We did an in-place move, so dex is ready to roll
18758            scanFlags |= SCAN_NO_DEX;
18759            scanFlags |= SCAN_MOVE;
18760
18761            synchronized (mPackages) {
18762                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18763                if (ps == null) {
18764                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18765                            "Missing settings for moved package " + pkgName);
18766                }
18767
18768                // We moved the entire application as-is, so bring over the
18769                // previously derived ABI information.
18770                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18771                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18772            }
18773
18774        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18775            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18776            scanFlags |= SCAN_NO_DEX;
18777
18778            try {
18779                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18780                    args.abiOverride : pkg.cpuAbiOverride);
18781                final boolean extractNativeLibs = !pkg.isLibrary();
18782                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18783                        extractNativeLibs, mAppLib32InstallDir);
18784            } catch (PackageManagerException pme) {
18785                Slog.e(TAG, "Error deriving application ABI", pme);
18786                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18787                return;
18788            }
18789
18790            // Shared libraries for the package need to be updated.
18791            synchronized (mPackages) {
18792                try {
18793                    updateSharedLibrariesLPr(pkg, null);
18794                } catch (PackageManagerException e) {
18795                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18796                }
18797            }
18798        }
18799
18800        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18801            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18802            return;
18803        }
18804
18805        if (!instantApp) {
18806            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18807        } else {
18808            if (DEBUG_DOMAIN_VERIFICATION) {
18809                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
18810            }
18811        }
18812
18813        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18814                "installPackageLI")) {
18815            if (replace) {
18816                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18817                    // Static libs have a synthetic package name containing the version
18818                    // and cannot be updated as an update would get a new package name,
18819                    // unless this is the exact same version code which is useful for
18820                    // development.
18821                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18822                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18823                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18824                                + "static-shared libs cannot be updated");
18825                        return;
18826                    }
18827                }
18828                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18829                        installerPackageName, res, args.installReason);
18830            } else {
18831                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18832                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18833            }
18834        }
18835
18836        // Prepare the application profiles for the new code paths.
18837        // This needs to be done before invoking dexopt so that any install-time profile
18838        // can be used for optimizations.
18839        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
18840
18841        // Check whether we need to dexopt the app.
18842        //
18843        // NOTE: it is IMPORTANT to call dexopt:
18844        //   - after doRename which will sync the package data from PackageParser.Package and its
18845        //     corresponding ApplicationInfo.
18846        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
18847        //     uid of the application (pkg.applicationInfo.uid).
18848        //     This update happens in place!
18849        //
18850        // We only need to dexopt if the package meets ALL of the following conditions:
18851        //   1) it is not forward locked.
18852        //   2) it is not on on an external ASEC container.
18853        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18854        //
18855        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18856        // complete, so we skip this step during installation. Instead, we'll take extra time
18857        // the first time the instant app starts. It's preferred to do it this way to provide
18858        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18859        // middle of running an instant app. The default behaviour can be overridden
18860        // via gservices.
18861        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
18862                && !forwardLocked
18863                && !pkg.applicationInfo.isExternalAsec()
18864                && (!instantApp || Global.getInt(mContext.getContentResolver(),
18865                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18866
18867        if (performDexopt) {
18868            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18869            // Do not run PackageDexOptimizer through the local performDexOpt
18870            // method because `pkg` may not be in `mPackages` yet.
18871            //
18872            // Also, don't fail application installs if the dexopt step fails.
18873            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18874                    REASON_INSTALL,
18875                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
18876                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
18877            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18878                    null /* instructionSets */,
18879                    getOrCreateCompilerPackageStats(pkg),
18880                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18881                    dexoptOptions);
18882            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18883        }
18884
18885        // Notify BackgroundDexOptService that the package has been changed.
18886        // If this is an update of a package which used to fail to compile,
18887        // BackgroundDexOptService will remove it from its blacklist.
18888        // TODO: Layering violation
18889        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18890
18891        synchronized (mPackages) {
18892            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18893            if (ps != null) {
18894                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18895                ps.setUpdateAvailable(false /*updateAvailable*/);
18896            }
18897
18898            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18899            for (int i = 0; i < childCount; i++) {
18900                PackageParser.Package childPkg = pkg.childPackages.get(i);
18901                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18902                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18903                if (childPs != null) {
18904                    childRes.newUsers = childPs.queryInstalledUsers(
18905                            sUserManager.getUserIds(), true);
18906                }
18907            }
18908
18909            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18910                updateSequenceNumberLP(ps, res.newUsers);
18911                updateInstantAppInstallerLocked(pkgName);
18912            }
18913        }
18914    }
18915
18916    private void startIntentFilterVerifications(int userId, boolean replacing,
18917            PackageParser.Package pkg) {
18918        if (mIntentFilterVerifierComponent == null) {
18919            Slog.w(TAG, "No IntentFilter verification will not be done as "
18920                    + "there is no IntentFilterVerifier available!");
18921            return;
18922        }
18923
18924        final int verifierUid = getPackageUid(
18925                mIntentFilterVerifierComponent.getPackageName(),
18926                MATCH_DEBUG_TRIAGED_MISSING,
18927                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18928
18929        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18930        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18931        mHandler.sendMessage(msg);
18932
18933        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18934        for (int i = 0; i < childCount; i++) {
18935            PackageParser.Package childPkg = pkg.childPackages.get(i);
18936            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18937            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18938            mHandler.sendMessage(msg);
18939        }
18940    }
18941
18942    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18943            PackageParser.Package pkg) {
18944        int size = pkg.activities.size();
18945        if (size == 0) {
18946            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18947                    "No activity, so no need to verify any IntentFilter!");
18948            return;
18949        }
18950
18951        final boolean hasDomainURLs = hasDomainURLs(pkg);
18952        if (!hasDomainURLs) {
18953            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18954                    "No domain URLs, so no need to verify any IntentFilter!");
18955            return;
18956        }
18957
18958        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18959                + " if any IntentFilter from the " + size
18960                + " Activities needs verification ...");
18961
18962        int count = 0;
18963        final String packageName = pkg.packageName;
18964
18965        synchronized (mPackages) {
18966            // If this is a new install and we see that we've already run verification for this
18967            // package, we have nothing to do: it means the state was restored from backup.
18968            if (!replacing) {
18969                IntentFilterVerificationInfo ivi =
18970                        mSettings.getIntentFilterVerificationLPr(packageName);
18971                if (ivi != null) {
18972                    if (DEBUG_DOMAIN_VERIFICATION) {
18973                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18974                                + ivi.getStatusString());
18975                    }
18976                    return;
18977                }
18978            }
18979
18980            // If any filters need to be verified, then all need to be.
18981            boolean needToVerify = false;
18982            for (PackageParser.Activity a : pkg.activities) {
18983                for (ActivityIntentInfo filter : a.intents) {
18984                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18985                        if (DEBUG_DOMAIN_VERIFICATION) {
18986                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18987                        }
18988                        needToVerify = true;
18989                        break;
18990                    }
18991                }
18992            }
18993
18994            if (needToVerify) {
18995                final int verificationId = mIntentFilterVerificationToken++;
18996                for (PackageParser.Activity a : pkg.activities) {
18997                    for (ActivityIntentInfo filter : a.intents) {
18998                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18999                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
19000                                    "Verification needed for IntentFilter:" + filter.toString());
19001                            mIntentFilterVerifier.addOneIntentFilterVerification(
19002                                    verifierUid, userId, verificationId, filter, packageName);
19003                            count++;
19004                        }
19005                    }
19006                }
19007            }
19008        }
19009
19010        if (count > 0) {
19011            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
19012                    + " IntentFilter verification" + (count > 1 ? "s" : "")
19013                    +  " for userId:" + userId);
19014            mIntentFilterVerifier.startVerifications(userId);
19015        } else {
19016            if (DEBUG_DOMAIN_VERIFICATION) {
19017                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
19018            }
19019        }
19020    }
19021
19022    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
19023        final ComponentName cn  = filter.activity.getComponentName();
19024        final String packageName = cn.getPackageName();
19025
19026        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
19027                packageName);
19028        if (ivi == null) {
19029            return true;
19030        }
19031        int status = ivi.getStatus();
19032        switch (status) {
19033            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
19034            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
19035                return true;
19036
19037            default:
19038                // Nothing to do
19039                return false;
19040        }
19041    }
19042
19043    private static boolean isMultiArch(ApplicationInfo info) {
19044        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
19045    }
19046
19047    private static boolean isExternal(PackageParser.Package pkg) {
19048        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19049    }
19050
19051    private static boolean isExternal(PackageSetting ps) {
19052        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19053    }
19054
19055    private static boolean isSystemApp(PackageParser.Package pkg) {
19056        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
19057    }
19058
19059    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
19060        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
19061    }
19062
19063    private static boolean hasDomainURLs(PackageParser.Package pkg) {
19064        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
19065    }
19066
19067    private static boolean isSystemApp(PackageSetting ps) {
19068        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
19069    }
19070
19071    private static boolean isUpdatedSystemApp(PackageSetting ps) {
19072        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
19073    }
19074
19075    private int packageFlagsToInstallFlags(PackageSetting ps) {
19076        int installFlags = 0;
19077        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
19078            // This existing package was an external ASEC install when we have
19079            // the external flag without a UUID
19080            installFlags |= PackageManager.INSTALL_EXTERNAL;
19081        }
19082        if (ps.isForwardLocked()) {
19083            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
19084        }
19085        return installFlags;
19086    }
19087
19088    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
19089        if (isExternal(pkg)) {
19090            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19091                return StorageManager.UUID_PRIMARY_PHYSICAL;
19092            } else {
19093                return pkg.volumeUuid;
19094            }
19095        } else {
19096            return StorageManager.UUID_PRIVATE_INTERNAL;
19097        }
19098    }
19099
19100    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
19101        if (isExternal(pkg)) {
19102            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19103                return mSettings.getExternalVersion();
19104            } else {
19105                return mSettings.findOrCreateVersion(pkg.volumeUuid);
19106            }
19107        } else {
19108            return mSettings.getInternalVersion();
19109        }
19110    }
19111
19112    private void deleteTempPackageFiles() {
19113        final FilenameFilter filter = new FilenameFilter() {
19114            public boolean accept(File dir, String name) {
19115                return name.startsWith("vmdl") && name.endsWith(".tmp");
19116            }
19117        };
19118        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
19119            file.delete();
19120        }
19121    }
19122
19123    @Override
19124    public void deletePackageAsUser(String packageName, int versionCode,
19125            IPackageDeleteObserver observer, int userId, int flags) {
19126        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
19127                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
19128    }
19129
19130    @Override
19131    public void deletePackageVersioned(VersionedPackage versionedPackage,
19132            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
19133        final int callingUid = Binder.getCallingUid();
19134        mContext.enforceCallingOrSelfPermission(
19135                android.Manifest.permission.DELETE_PACKAGES, null);
19136        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
19137        Preconditions.checkNotNull(versionedPackage);
19138        Preconditions.checkNotNull(observer);
19139        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
19140                PackageManager.VERSION_CODE_HIGHEST,
19141                Integer.MAX_VALUE, "versionCode must be >= -1");
19142
19143        final String packageName = versionedPackage.getPackageName();
19144        final int versionCode = versionedPackage.getVersionCode();
19145        final String internalPackageName;
19146        synchronized (mPackages) {
19147            // Normalize package name to handle renamed packages and static libs
19148            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19149                    versionedPackage.getVersionCode());
19150        }
19151
19152        final int uid = Binder.getCallingUid();
19153        if (!isOrphaned(internalPackageName)
19154                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19155            try {
19156                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19157                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19158                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19159                observer.onUserActionRequired(intent);
19160            } catch (RemoteException re) {
19161            }
19162            return;
19163        }
19164        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19165        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19166        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19167            mContext.enforceCallingOrSelfPermission(
19168                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19169                    "deletePackage for user " + userId);
19170        }
19171
19172        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19173            try {
19174                observer.onPackageDeleted(packageName,
19175                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19176            } catch (RemoteException re) {
19177            }
19178            return;
19179        }
19180
19181        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19182            try {
19183                observer.onPackageDeleted(packageName,
19184                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19185            } catch (RemoteException re) {
19186            }
19187            return;
19188        }
19189
19190        if (DEBUG_REMOVE) {
19191            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19192                    + " deleteAllUsers: " + deleteAllUsers + " version="
19193                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19194                    ? "VERSION_CODE_HIGHEST" : versionCode));
19195        }
19196        // Queue up an async operation since the package deletion may take a little while.
19197        mHandler.post(new Runnable() {
19198            public void run() {
19199                mHandler.removeCallbacks(this);
19200                int returnCode;
19201                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19202                boolean doDeletePackage = true;
19203                if (ps != null) {
19204                    final boolean targetIsInstantApp =
19205                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19206                    doDeletePackage = !targetIsInstantApp
19207                            || canViewInstantApps;
19208                }
19209                if (doDeletePackage) {
19210                    if (!deleteAllUsers) {
19211                        returnCode = deletePackageX(internalPackageName, versionCode,
19212                                userId, deleteFlags);
19213                    } else {
19214                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19215                                internalPackageName, users);
19216                        // If nobody is blocking uninstall, proceed with delete for all users
19217                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19218                            returnCode = deletePackageX(internalPackageName, versionCode,
19219                                    userId, deleteFlags);
19220                        } else {
19221                            // Otherwise uninstall individually for users with blockUninstalls=false
19222                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19223                            for (int userId : users) {
19224                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19225                                    returnCode = deletePackageX(internalPackageName, versionCode,
19226                                            userId, userFlags);
19227                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19228                                        Slog.w(TAG, "Package delete failed for user " + userId
19229                                                + ", returnCode " + returnCode);
19230                                    }
19231                                }
19232                            }
19233                            // The app has only been marked uninstalled for certain users.
19234                            // We still need to report that delete was blocked
19235                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19236                        }
19237                    }
19238                } else {
19239                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19240                }
19241                try {
19242                    observer.onPackageDeleted(packageName, returnCode, null);
19243                } catch (RemoteException e) {
19244                    Log.i(TAG, "Observer no longer exists.");
19245                } //end catch
19246            } //end run
19247        });
19248    }
19249
19250    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19251        if (pkg.staticSharedLibName != null) {
19252            return pkg.manifestPackageName;
19253        }
19254        return pkg.packageName;
19255    }
19256
19257    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19258        // Handle renamed packages
19259        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19260        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19261
19262        // Is this a static library?
19263        SparseArray<SharedLibraryEntry> versionedLib =
19264                mStaticLibsByDeclaringPackage.get(packageName);
19265        if (versionedLib == null || versionedLib.size() <= 0) {
19266            return packageName;
19267        }
19268
19269        // Figure out which lib versions the caller can see
19270        SparseIntArray versionsCallerCanSee = null;
19271        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19272        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19273                && callingAppId != Process.ROOT_UID) {
19274            versionsCallerCanSee = new SparseIntArray();
19275            String libName = versionedLib.valueAt(0).info.getName();
19276            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19277            if (uidPackages != null) {
19278                for (String uidPackage : uidPackages) {
19279                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19280                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19281                    if (libIdx >= 0) {
19282                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19283                        versionsCallerCanSee.append(libVersion, libVersion);
19284                    }
19285                }
19286            }
19287        }
19288
19289        // Caller can see nothing - done
19290        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19291            return packageName;
19292        }
19293
19294        // Find the version the caller can see and the app version code
19295        SharedLibraryEntry highestVersion = null;
19296        final int versionCount = versionedLib.size();
19297        for (int i = 0; i < versionCount; i++) {
19298            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19299            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19300                    libEntry.info.getVersion()) < 0) {
19301                continue;
19302            }
19303            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19304            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19305                if (libVersionCode == versionCode) {
19306                    return libEntry.apk;
19307                }
19308            } else if (highestVersion == null) {
19309                highestVersion = libEntry;
19310            } else if (libVersionCode  > highestVersion.info
19311                    .getDeclaringPackage().getVersionCode()) {
19312                highestVersion = libEntry;
19313            }
19314        }
19315
19316        if (highestVersion != null) {
19317            return highestVersion.apk;
19318        }
19319
19320        return packageName;
19321    }
19322
19323    boolean isCallerVerifier(int callingUid) {
19324        final int callingUserId = UserHandle.getUserId(callingUid);
19325        return mRequiredVerifierPackage != null &&
19326                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19327    }
19328
19329    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19330        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19331              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19332            return true;
19333        }
19334        final int callingUserId = UserHandle.getUserId(callingUid);
19335        // If the caller installed the pkgName, then allow it to silently uninstall.
19336        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19337            return true;
19338        }
19339
19340        // Allow package verifier to silently uninstall.
19341        if (mRequiredVerifierPackage != null &&
19342                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19343            return true;
19344        }
19345
19346        // Allow package uninstaller to silently uninstall.
19347        if (mRequiredUninstallerPackage != null &&
19348                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19349            return true;
19350        }
19351
19352        // Allow storage manager to silently uninstall.
19353        if (mStorageManagerPackage != null &&
19354                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19355            return true;
19356        }
19357
19358        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19359        // uninstall for device owner provisioning.
19360        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19361                == PERMISSION_GRANTED) {
19362            return true;
19363        }
19364
19365        return false;
19366    }
19367
19368    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19369        int[] result = EMPTY_INT_ARRAY;
19370        for (int userId : userIds) {
19371            if (getBlockUninstallForUser(packageName, userId)) {
19372                result = ArrayUtils.appendInt(result, userId);
19373            }
19374        }
19375        return result;
19376    }
19377
19378    @Override
19379    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19380        final int callingUid = Binder.getCallingUid();
19381        if (getInstantAppPackageName(callingUid) != null
19382                && !isCallerSameApp(packageName, callingUid)) {
19383            return false;
19384        }
19385        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19386    }
19387
19388    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19389        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19390                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19391        try {
19392            if (dpm != null) {
19393                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19394                        /* callingUserOnly =*/ false);
19395                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19396                        : deviceOwnerComponentName.getPackageName();
19397                // Does the package contains the device owner?
19398                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19399                // this check is probably not needed, since DO should be registered as a device
19400                // admin on some user too. (Original bug for this: b/17657954)
19401                if (packageName.equals(deviceOwnerPackageName)) {
19402                    return true;
19403                }
19404                // Does it contain a device admin for any user?
19405                int[] users;
19406                if (userId == UserHandle.USER_ALL) {
19407                    users = sUserManager.getUserIds();
19408                } else {
19409                    users = new int[]{userId};
19410                }
19411                for (int i = 0; i < users.length; ++i) {
19412                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19413                        return true;
19414                    }
19415                }
19416            }
19417        } catch (RemoteException e) {
19418        }
19419        return false;
19420    }
19421
19422    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19423        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19424    }
19425
19426    /**
19427     *  This method is an internal method that could be get invoked either
19428     *  to delete an installed package or to clean up a failed installation.
19429     *  After deleting an installed package, a broadcast is sent to notify any
19430     *  listeners that the package has been removed. For cleaning up a failed
19431     *  installation, the broadcast is not necessary since the package's
19432     *  installation wouldn't have sent the initial broadcast either
19433     *  The key steps in deleting a package are
19434     *  deleting the package information in internal structures like mPackages,
19435     *  deleting the packages base directories through installd
19436     *  updating mSettings to reflect current status
19437     *  persisting settings for later use
19438     *  sending a broadcast if necessary
19439     */
19440    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19441        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19442        final boolean res;
19443
19444        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19445                ? UserHandle.USER_ALL : userId;
19446
19447        if (isPackageDeviceAdmin(packageName, removeUser)) {
19448            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19449            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19450        }
19451
19452        PackageSetting uninstalledPs = null;
19453        PackageParser.Package pkg = null;
19454
19455        // for the uninstall-updates case and restricted profiles, remember the per-
19456        // user handle installed state
19457        int[] allUsers;
19458        synchronized (mPackages) {
19459            uninstalledPs = mSettings.mPackages.get(packageName);
19460            if (uninstalledPs == null) {
19461                Slog.w(TAG, "Not removing non-existent package " + packageName);
19462                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19463            }
19464
19465            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19466                    && uninstalledPs.versionCode != versionCode) {
19467                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19468                        + uninstalledPs.versionCode + " != " + versionCode);
19469                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19470            }
19471
19472            // Static shared libs can be declared by any package, so let us not
19473            // allow removing a package if it provides a lib others depend on.
19474            pkg = mPackages.get(packageName);
19475
19476            allUsers = sUserManager.getUserIds();
19477
19478            if (pkg != null && pkg.staticSharedLibName != null) {
19479                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19480                        pkg.staticSharedLibVersion);
19481                if (libEntry != null) {
19482                    for (int currUserId : allUsers) {
19483                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19484                            continue;
19485                        }
19486                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19487                                libEntry.info, 0, currUserId);
19488                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19489                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19490                                    + " hosting lib " + libEntry.info.getName() + " version "
19491                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19492                                    + " for user " + currUserId);
19493                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19494                        }
19495                    }
19496                }
19497            }
19498
19499            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19500        }
19501
19502        final int freezeUser;
19503        if (isUpdatedSystemApp(uninstalledPs)
19504                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19505            // We're downgrading a system app, which will apply to all users, so
19506            // freeze them all during the downgrade
19507            freezeUser = UserHandle.USER_ALL;
19508        } else {
19509            freezeUser = removeUser;
19510        }
19511
19512        synchronized (mInstallLock) {
19513            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19514            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19515                    deleteFlags, "deletePackageX")) {
19516                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19517                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19518            }
19519            synchronized (mPackages) {
19520                if (res) {
19521                    if (pkg != null) {
19522                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19523                    }
19524                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19525                    updateInstantAppInstallerLocked(packageName);
19526                }
19527            }
19528        }
19529
19530        if (res) {
19531            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19532            info.sendPackageRemovedBroadcasts(killApp);
19533            info.sendSystemPackageUpdatedBroadcasts();
19534            info.sendSystemPackageAppearedBroadcasts();
19535        }
19536        // Force a gc here.
19537        Runtime.getRuntime().gc();
19538        // Delete the resources here after sending the broadcast to let
19539        // other processes clean up before deleting resources.
19540        if (info.args != null) {
19541            synchronized (mInstallLock) {
19542                info.args.doPostDeleteLI(true);
19543            }
19544        }
19545
19546        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19547    }
19548
19549    static class PackageRemovedInfo {
19550        final PackageSender packageSender;
19551        String removedPackage;
19552        String installerPackageName;
19553        int uid = -1;
19554        int removedAppId = -1;
19555        int[] origUsers;
19556        int[] removedUsers = null;
19557        int[] broadcastUsers = null;
19558        SparseArray<Integer> installReasons;
19559        boolean isRemovedPackageSystemUpdate = false;
19560        boolean isUpdate;
19561        boolean dataRemoved;
19562        boolean removedForAllUsers;
19563        boolean isStaticSharedLib;
19564        // Clean up resources deleted packages.
19565        InstallArgs args = null;
19566        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19567        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19568
19569        PackageRemovedInfo(PackageSender packageSender) {
19570            this.packageSender = packageSender;
19571        }
19572
19573        void sendPackageRemovedBroadcasts(boolean killApp) {
19574            sendPackageRemovedBroadcastInternal(killApp);
19575            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19576            for (int i = 0; i < childCount; i++) {
19577                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19578                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19579            }
19580        }
19581
19582        void sendSystemPackageUpdatedBroadcasts() {
19583            if (isRemovedPackageSystemUpdate) {
19584                sendSystemPackageUpdatedBroadcastsInternal();
19585                final int childCount = (removedChildPackages != null)
19586                        ? removedChildPackages.size() : 0;
19587                for (int i = 0; i < childCount; i++) {
19588                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19589                    if (childInfo.isRemovedPackageSystemUpdate) {
19590                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19591                    }
19592                }
19593            }
19594        }
19595
19596        void sendSystemPackageAppearedBroadcasts() {
19597            final int packageCount = (appearedChildPackages != null)
19598                    ? appearedChildPackages.size() : 0;
19599            for (int i = 0; i < packageCount; i++) {
19600                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19601                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19602                    true /*sendBootCompleted*/, false /*startReceiver*/,
19603                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19604            }
19605        }
19606
19607        private void sendSystemPackageUpdatedBroadcastsInternal() {
19608            Bundle extras = new Bundle(2);
19609            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19610            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19611            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19612                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19613            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19614                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19615            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19616                null, null, 0, removedPackage, null, null);
19617            if (installerPackageName != null) {
19618                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19619                        removedPackage, extras, 0 /*flags*/,
19620                        installerPackageName, null, null);
19621                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19622                        removedPackage, extras, 0 /*flags*/,
19623                        installerPackageName, null, null);
19624            }
19625        }
19626
19627        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19628            // Don't send static shared library removal broadcasts as these
19629            // libs are visible only the the apps that depend on them an one
19630            // cannot remove the library if it has a dependency.
19631            if (isStaticSharedLib) {
19632                return;
19633            }
19634            Bundle extras = new Bundle(2);
19635            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19636            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19637            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19638            if (isUpdate || isRemovedPackageSystemUpdate) {
19639                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19640            }
19641            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19642            if (removedPackage != null) {
19643                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19644                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19645                if (installerPackageName != null) {
19646                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19647                            removedPackage, extras, 0 /*flags*/,
19648                            installerPackageName, null, broadcastUsers);
19649                }
19650                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19651                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19652                        removedPackage, extras,
19653                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19654                        null, null, broadcastUsers);
19655                }
19656            }
19657            if (removedAppId >= 0) {
19658                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19659                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19660                    null, null, broadcastUsers);
19661            }
19662        }
19663
19664        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19665            removedUsers = userIds;
19666            if (removedUsers == null) {
19667                broadcastUsers = null;
19668                return;
19669            }
19670
19671            broadcastUsers = EMPTY_INT_ARRAY;
19672            for (int i = userIds.length - 1; i >= 0; --i) {
19673                final int userId = userIds[i];
19674                if (deletedPackageSetting.getInstantApp(userId)) {
19675                    continue;
19676                }
19677                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19678            }
19679        }
19680    }
19681
19682    /*
19683     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19684     * flag is not set, the data directory is removed as well.
19685     * make sure this flag is set for partially installed apps. If not its meaningless to
19686     * delete a partially installed application.
19687     */
19688    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19689            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19690        String packageName = ps.name;
19691        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19692        // Retrieve object to delete permissions for shared user later on
19693        final PackageParser.Package deletedPkg;
19694        final PackageSetting deletedPs;
19695        // reader
19696        synchronized (mPackages) {
19697            deletedPkg = mPackages.get(packageName);
19698            deletedPs = mSettings.mPackages.get(packageName);
19699            if (outInfo != null) {
19700                outInfo.removedPackage = packageName;
19701                outInfo.installerPackageName = ps.installerPackageName;
19702                outInfo.isStaticSharedLib = deletedPkg != null
19703                        && deletedPkg.staticSharedLibName != null;
19704                outInfo.populateUsers(deletedPs == null ? null
19705                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19706            }
19707        }
19708
19709        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19710
19711        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19712            final PackageParser.Package resolvedPkg;
19713            if (deletedPkg != null) {
19714                resolvedPkg = deletedPkg;
19715            } else {
19716                // We don't have a parsed package when it lives on an ejected
19717                // adopted storage device, so fake something together
19718                resolvedPkg = new PackageParser.Package(ps.name);
19719                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19720            }
19721            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19722                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19723            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19724            if (outInfo != null) {
19725                outInfo.dataRemoved = true;
19726            }
19727            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19728        }
19729
19730        int removedAppId = -1;
19731
19732        // writer
19733        synchronized (mPackages) {
19734            boolean installedStateChanged = false;
19735            if (deletedPs != null) {
19736                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19737                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19738                    clearDefaultBrowserIfNeeded(packageName);
19739                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19740                    removedAppId = mSettings.removePackageLPw(packageName);
19741                    if (outInfo != null) {
19742                        outInfo.removedAppId = removedAppId;
19743                    }
19744                    updatePermissionsLPw(deletedPs.name, null, 0);
19745                    if (deletedPs.sharedUser != null) {
19746                        // Remove permissions associated with package. Since runtime
19747                        // permissions are per user we have to kill the removed package
19748                        // or packages running under the shared user of the removed
19749                        // package if revoking the permissions requested only by the removed
19750                        // package is successful and this causes a change in gids.
19751                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19752                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19753                                    userId);
19754                            if (userIdToKill == UserHandle.USER_ALL
19755                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19756                                // If gids changed for this user, kill all affected packages.
19757                                mHandler.post(new Runnable() {
19758                                    @Override
19759                                    public void run() {
19760                                        // This has to happen with no lock held.
19761                                        killApplication(deletedPs.name, deletedPs.appId,
19762                                                KILL_APP_REASON_GIDS_CHANGED);
19763                                    }
19764                                });
19765                                break;
19766                            }
19767                        }
19768                    }
19769                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19770                }
19771                // make sure to preserve per-user disabled state if this removal was just
19772                // a downgrade of a system app to the factory package
19773                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19774                    if (DEBUG_REMOVE) {
19775                        Slog.d(TAG, "Propagating install state across downgrade");
19776                    }
19777                    for (int userId : allUserHandles) {
19778                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19779                        if (DEBUG_REMOVE) {
19780                            Slog.d(TAG, "    user " + userId + " => " + installed);
19781                        }
19782                        if (installed != ps.getInstalled(userId)) {
19783                            installedStateChanged = true;
19784                        }
19785                        ps.setInstalled(installed, userId);
19786                    }
19787                }
19788            }
19789            // can downgrade to reader
19790            if (writeSettings) {
19791                // Save settings now
19792                mSettings.writeLPr();
19793            }
19794            if (installedStateChanged) {
19795                mSettings.writeKernelMappingLPr(ps);
19796            }
19797        }
19798        if (removedAppId != -1) {
19799            // A user ID was deleted here. Go through all users and remove it
19800            // from KeyStore.
19801            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19802        }
19803    }
19804
19805    static boolean locationIsPrivileged(File path) {
19806        try {
19807            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19808                    .getCanonicalPath();
19809            return path.getCanonicalPath().startsWith(privilegedAppDir);
19810        } catch (IOException e) {
19811            Slog.e(TAG, "Unable to access code path " + path);
19812        }
19813        return false;
19814    }
19815
19816    /*
19817     * Tries to delete system package.
19818     */
19819    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19820            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19821            boolean writeSettings) {
19822        if (deletedPs.parentPackageName != null) {
19823            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19824            return false;
19825        }
19826
19827        final boolean applyUserRestrictions
19828                = (allUserHandles != null) && (outInfo.origUsers != null);
19829        final PackageSetting disabledPs;
19830        // Confirm if the system package has been updated
19831        // An updated system app can be deleted. This will also have to restore
19832        // the system pkg from system partition
19833        // reader
19834        synchronized (mPackages) {
19835            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19836        }
19837
19838        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19839                + " disabledPs=" + disabledPs);
19840
19841        if (disabledPs == null) {
19842            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19843            return false;
19844        } else if (DEBUG_REMOVE) {
19845            Slog.d(TAG, "Deleting system pkg from data partition");
19846        }
19847
19848        if (DEBUG_REMOVE) {
19849            if (applyUserRestrictions) {
19850                Slog.d(TAG, "Remembering install states:");
19851                for (int userId : allUserHandles) {
19852                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19853                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19854                }
19855            }
19856        }
19857
19858        // Delete the updated package
19859        outInfo.isRemovedPackageSystemUpdate = true;
19860        if (outInfo.removedChildPackages != null) {
19861            final int childCount = (deletedPs.childPackageNames != null)
19862                    ? deletedPs.childPackageNames.size() : 0;
19863            for (int i = 0; i < childCount; i++) {
19864                String childPackageName = deletedPs.childPackageNames.get(i);
19865                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19866                        .contains(childPackageName)) {
19867                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19868                            childPackageName);
19869                    if (childInfo != null) {
19870                        childInfo.isRemovedPackageSystemUpdate = true;
19871                    }
19872                }
19873            }
19874        }
19875
19876        if (disabledPs.versionCode < deletedPs.versionCode) {
19877            // Delete data for downgrades
19878            flags &= ~PackageManager.DELETE_KEEP_DATA;
19879        } else {
19880            // Preserve data by setting flag
19881            flags |= PackageManager.DELETE_KEEP_DATA;
19882        }
19883
19884        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19885                outInfo, writeSettings, disabledPs.pkg);
19886        if (!ret) {
19887            return false;
19888        }
19889
19890        // writer
19891        synchronized (mPackages) {
19892            // NOTE: The system package always needs to be enabled; even if it's for
19893            // a compressed stub. If we don't, installing the system package fails
19894            // during scan [scanning checks the disabled packages]. We will reverse
19895            // this later, after we've "installed" the stub.
19896            // Reinstate the old system package
19897            enableSystemPackageLPw(disabledPs.pkg);
19898            // Remove any native libraries from the upgraded package.
19899            removeNativeBinariesLI(deletedPs);
19900        }
19901
19902        // Install the system package
19903        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19904        try {
19905            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19906                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19907        } catch (PackageManagerException e) {
19908            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19909                    + e.getMessage());
19910            return false;
19911        } finally {
19912            if (disabledPs.pkg.isStub) {
19913                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19914            }
19915        }
19916        return true;
19917    }
19918
19919    /**
19920     * Installs a package that's already on the system partition.
19921     */
19922    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19923            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19924            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19925                    throws PackageManagerException {
19926        int parseFlags = mDefParseFlags
19927                | PackageParser.PARSE_MUST_BE_APK
19928                | PackageParser.PARSE_IS_SYSTEM
19929                | PackageParser.PARSE_IS_SYSTEM_DIR;
19930        if (isPrivileged || locationIsPrivileged(codePath)) {
19931            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19932        }
19933
19934        final PackageParser.Package newPkg =
19935                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19936
19937        try {
19938            // update shared libraries for the newly re-installed system package
19939            updateSharedLibrariesLPr(newPkg, null);
19940        } catch (PackageManagerException e) {
19941            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19942        }
19943
19944        prepareAppDataAfterInstallLIF(newPkg);
19945
19946        // writer
19947        synchronized (mPackages) {
19948            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19949
19950            // Propagate the permissions state as we do not want to drop on the floor
19951            // runtime permissions. The update permissions method below will take
19952            // care of removing obsolete permissions and grant install permissions.
19953            if (origPermissionState != null) {
19954                ps.getPermissionsState().copyFrom(origPermissionState);
19955            }
19956            updatePermissionsLPw(newPkg.packageName, newPkg,
19957                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19958
19959            final boolean applyUserRestrictions
19960                    = (allUserHandles != null) && (origUserHandles != null);
19961            if (applyUserRestrictions) {
19962                boolean installedStateChanged = false;
19963                if (DEBUG_REMOVE) {
19964                    Slog.d(TAG, "Propagating install state across reinstall");
19965                }
19966                for (int userId : allUserHandles) {
19967                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19968                    if (DEBUG_REMOVE) {
19969                        Slog.d(TAG, "    user " + userId + " => " + installed);
19970                    }
19971                    if (installed != ps.getInstalled(userId)) {
19972                        installedStateChanged = true;
19973                    }
19974                    ps.setInstalled(installed, userId);
19975
19976                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19977                }
19978                // Regardless of writeSettings we need to ensure that this restriction
19979                // state propagation is persisted
19980                mSettings.writeAllUsersPackageRestrictionsLPr();
19981                if (installedStateChanged) {
19982                    mSettings.writeKernelMappingLPr(ps);
19983                }
19984            }
19985            // can downgrade to reader here
19986            if (writeSettings) {
19987                mSettings.writeLPr();
19988            }
19989        }
19990        return newPkg;
19991    }
19992
19993    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19994            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19995            PackageRemovedInfo outInfo, boolean writeSettings,
19996            PackageParser.Package replacingPackage) {
19997        synchronized (mPackages) {
19998            if (outInfo != null) {
19999                outInfo.uid = ps.appId;
20000            }
20001
20002            if (outInfo != null && outInfo.removedChildPackages != null) {
20003                final int childCount = (ps.childPackageNames != null)
20004                        ? ps.childPackageNames.size() : 0;
20005                for (int i = 0; i < childCount; i++) {
20006                    String childPackageName = ps.childPackageNames.get(i);
20007                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
20008                    if (childPs == null) {
20009                        return false;
20010                    }
20011                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
20012                            childPackageName);
20013                    if (childInfo != null) {
20014                        childInfo.uid = childPs.appId;
20015                    }
20016                }
20017            }
20018        }
20019
20020        // Delete package data from internal structures and also remove data if flag is set
20021        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
20022
20023        // Delete the child packages data
20024        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
20025        for (int i = 0; i < childCount; i++) {
20026            PackageSetting childPs;
20027            synchronized (mPackages) {
20028                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
20029            }
20030            if (childPs != null) {
20031                PackageRemovedInfo childOutInfo = (outInfo != null
20032                        && outInfo.removedChildPackages != null)
20033                        ? outInfo.removedChildPackages.get(childPs.name) : null;
20034                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
20035                        && (replacingPackage != null
20036                        && !replacingPackage.hasChildPackage(childPs.name))
20037                        ? flags & ~DELETE_KEEP_DATA : flags;
20038                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
20039                        deleteFlags, writeSettings);
20040            }
20041        }
20042
20043        // Delete application code and resources only for parent packages
20044        if (ps.parentPackageName == null) {
20045            if (deleteCodeAndResources && (outInfo != null)) {
20046                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
20047                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
20048                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
20049            }
20050        }
20051
20052        return true;
20053    }
20054
20055    @Override
20056    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
20057            int userId) {
20058        mContext.enforceCallingOrSelfPermission(
20059                android.Manifest.permission.DELETE_PACKAGES, null);
20060        synchronized (mPackages) {
20061            // Cannot block uninstall of static shared libs as they are
20062            // considered a part of the using app (emulating static linking).
20063            // Also static libs are installed always on internal storage.
20064            PackageParser.Package pkg = mPackages.get(packageName);
20065            if (pkg != null && pkg.staticSharedLibName != null) {
20066                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
20067                        + " providing static shared library: " + pkg.staticSharedLibName);
20068                return false;
20069            }
20070            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
20071            mSettings.writePackageRestrictionsLPr(userId);
20072        }
20073        return true;
20074    }
20075
20076    @Override
20077    public boolean getBlockUninstallForUser(String packageName, int userId) {
20078        synchronized (mPackages) {
20079            final PackageSetting ps = mSettings.mPackages.get(packageName);
20080            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
20081                return false;
20082            }
20083            return mSettings.getBlockUninstallLPr(userId, packageName);
20084        }
20085    }
20086
20087    @Override
20088    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
20089        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
20090        synchronized (mPackages) {
20091            PackageSetting ps = mSettings.mPackages.get(packageName);
20092            if (ps == null) {
20093                Log.w(TAG, "Package doesn't exist: " + packageName);
20094                return false;
20095            }
20096            if (systemUserApp) {
20097                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20098            } else {
20099                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20100            }
20101            mSettings.writeLPr();
20102        }
20103        return true;
20104    }
20105
20106    /*
20107     * This method handles package deletion in general
20108     */
20109    private boolean deletePackageLIF(String packageName, UserHandle user,
20110            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
20111            PackageRemovedInfo outInfo, boolean writeSettings,
20112            PackageParser.Package replacingPackage) {
20113        if (packageName == null) {
20114            Slog.w(TAG, "Attempt to delete null packageName.");
20115            return false;
20116        }
20117
20118        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
20119
20120        PackageSetting ps;
20121        synchronized (mPackages) {
20122            ps = mSettings.mPackages.get(packageName);
20123            if (ps == null) {
20124                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20125                return false;
20126            }
20127
20128            if (ps.parentPackageName != null && (!isSystemApp(ps)
20129                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
20130                if (DEBUG_REMOVE) {
20131                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
20132                            + ((user == null) ? UserHandle.USER_ALL : user));
20133                }
20134                final int removedUserId = (user != null) ? user.getIdentifier()
20135                        : UserHandle.USER_ALL;
20136                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
20137                    return false;
20138                }
20139                markPackageUninstalledForUserLPw(ps, user);
20140                scheduleWritePackageRestrictionsLocked(user);
20141                return true;
20142            }
20143        }
20144
20145        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
20146                && user.getIdentifier() != UserHandle.USER_ALL)) {
20147            // The caller is asking that the package only be deleted for a single
20148            // user.  To do this, we just mark its uninstalled state and delete
20149            // its data. If this is a system app, we only allow this to happen if
20150            // they have set the special DELETE_SYSTEM_APP which requests different
20151            // semantics than normal for uninstalling system apps.
20152            markPackageUninstalledForUserLPw(ps, user);
20153
20154            if (!isSystemApp(ps)) {
20155                // Do not uninstall the APK if an app should be cached
20156                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
20157                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
20158                    // Other user still have this package installed, so all
20159                    // we need to do is clear this user's data and save that
20160                    // it is uninstalled.
20161                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
20162                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20163                        return false;
20164                    }
20165                    scheduleWritePackageRestrictionsLocked(user);
20166                    return true;
20167                } else {
20168                    // We need to set it back to 'installed' so the uninstall
20169                    // broadcasts will be sent correctly.
20170                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20171                    ps.setInstalled(true, user.getIdentifier());
20172                    mSettings.writeKernelMappingLPr(ps);
20173                }
20174            } else {
20175                // This is a system app, so we assume that the
20176                // other users still have this package installed, so all
20177                // we need to do is clear this user's data and save that
20178                // it is uninstalled.
20179                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20180                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20181                    return false;
20182                }
20183                scheduleWritePackageRestrictionsLocked(user);
20184                return true;
20185            }
20186        }
20187
20188        // If we are deleting a composite package for all users, keep track
20189        // of result for each child.
20190        if (ps.childPackageNames != null && outInfo != null) {
20191            synchronized (mPackages) {
20192                final int childCount = ps.childPackageNames.size();
20193                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20194                for (int i = 0; i < childCount; i++) {
20195                    String childPackageName = ps.childPackageNames.get(i);
20196                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20197                    childInfo.removedPackage = childPackageName;
20198                    childInfo.installerPackageName = ps.installerPackageName;
20199                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20200                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20201                    if (childPs != null) {
20202                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20203                    }
20204                }
20205            }
20206        }
20207
20208        boolean ret = false;
20209        if (isSystemApp(ps)) {
20210            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20211            // When an updated system application is deleted we delete the existing resources
20212            // as well and fall back to existing code in system partition
20213            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20214        } else {
20215            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20216            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20217                    outInfo, writeSettings, replacingPackage);
20218        }
20219
20220        // Take a note whether we deleted the package for all users
20221        if (outInfo != null) {
20222            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20223            if (outInfo.removedChildPackages != null) {
20224                synchronized (mPackages) {
20225                    final int childCount = outInfo.removedChildPackages.size();
20226                    for (int i = 0; i < childCount; i++) {
20227                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20228                        if (childInfo != null) {
20229                            childInfo.removedForAllUsers = mPackages.get(
20230                                    childInfo.removedPackage) == null;
20231                        }
20232                    }
20233                }
20234            }
20235            // If we uninstalled an update to a system app there may be some
20236            // child packages that appeared as they are declared in the system
20237            // app but were not declared in the update.
20238            if (isSystemApp(ps)) {
20239                synchronized (mPackages) {
20240                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20241                    final int childCount = (updatedPs.childPackageNames != null)
20242                            ? updatedPs.childPackageNames.size() : 0;
20243                    for (int i = 0; i < childCount; i++) {
20244                        String childPackageName = updatedPs.childPackageNames.get(i);
20245                        if (outInfo.removedChildPackages == null
20246                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20247                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20248                            if (childPs == null) {
20249                                continue;
20250                            }
20251                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20252                            installRes.name = childPackageName;
20253                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20254                            installRes.pkg = mPackages.get(childPackageName);
20255                            installRes.uid = childPs.pkg.applicationInfo.uid;
20256                            if (outInfo.appearedChildPackages == null) {
20257                                outInfo.appearedChildPackages = new ArrayMap<>();
20258                            }
20259                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20260                        }
20261                    }
20262                }
20263            }
20264        }
20265
20266        return ret;
20267    }
20268
20269    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20270        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20271                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20272        for (int nextUserId : userIds) {
20273            if (DEBUG_REMOVE) {
20274                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20275            }
20276            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20277                    false /*installed*/,
20278                    true /*stopped*/,
20279                    true /*notLaunched*/,
20280                    false /*hidden*/,
20281                    false /*suspended*/,
20282                    false /*instantApp*/,
20283                    false /*virtualPreload*/,
20284                    null /*lastDisableAppCaller*/,
20285                    null /*enabledComponents*/,
20286                    null /*disabledComponents*/,
20287                    ps.readUserState(nextUserId).domainVerificationStatus,
20288                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20289        }
20290        mSettings.writeKernelMappingLPr(ps);
20291    }
20292
20293    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20294            PackageRemovedInfo outInfo) {
20295        final PackageParser.Package pkg;
20296        synchronized (mPackages) {
20297            pkg = mPackages.get(ps.name);
20298        }
20299
20300        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20301                : new int[] {userId};
20302        for (int nextUserId : userIds) {
20303            if (DEBUG_REMOVE) {
20304                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20305                        + nextUserId);
20306            }
20307
20308            destroyAppDataLIF(pkg, userId,
20309                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20310            destroyAppProfilesLIF(pkg, userId);
20311            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20312            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20313            schedulePackageCleaning(ps.name, nextUserId, false);
20314            synchronized (mPackages) {
20315                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20316                    scheduleWritePackageRestrictionsLocked(nextUserId);
20317                }
20318                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20319            }
20320        }
20321
20322        if (outInfo != null) {
20323            outInfo.removedPackage = ps.name;
20324            outInfo.installerPackageName = ps.installerPackageName;
20325            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20326            outInfo.removedAppId = ps.appId;
20327            outInfo.removedUsers = userIds;
20328            outInfo.broadcastUsers = userIds;
20329        }
20330
20331        return true;
20332    }
20333
20334    private final class ClearStorageConnection implements ServiceConnection {
20335        IMediaContainerService mContainerService;
20336
20337        @Override
20338        public void onServiceConnected(ComponentName name, IBinder service) {
20339            synchronized (this) {
20340                mContainerService = IMediaContainerService.Stub
20341                        .asInterface(Binder.allowBlocking(service));
20342                notifyAll();
20343            }
20344        }
20345
20346        @Override
20347        public void onServiceDisconnected(ComponentName name) {
20348        }
20349    }
20350
20351    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20352        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20353
20354        final boolean mounted;
20355        if (Environment.isExternalStorageEmulated()) {
20356            mounted = true;
20357        } else {
20358            final String status = Environment.getExternalStorageState();
20359
20360            mounted = status.equals(Environment.MEDIA_MOUNTED)
20361                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20362        }
20363
20364        if (!mounted) {
20365            return;
20366        }
20367
20368        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20369        int[] users;
20370        if (userId == UserHandle.USER_ALL) {
20371            users = sUserManager.getUserIds();
20372        } else {
20373            users = new int[] { userId };
20374        }
20375        final ClearStorageConnection conn = new ClearStorageConnection();
20376        if (mContext.bindServiceAsUser(
20377                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20378            try {
20379                for (int curUser : users) {
20380                    long timeout = SystemClock.uptimeMillis() + 5000;
20381                    synchronized (conn) {
20382                        long now;
20383                        while (conn.mContainerService == null &&
20384                                (now = SystemClock.uptimeMillis()) < timeout) {
20385                            try {
20386                                conn.wait(timeout - now);
20387                            } catch (InterruptedException e) {
20388                            }
20389                        }
20390                    }
20391                    if (conn.mContainerService == null) {
20392                        return;
20393                    }
20394
20395                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20396                    clearDirectory(conn.mContainerService,
20397                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20398                    if (allData) {
20399                        clearDirectory(conn.mContainerService,
20400                                userEnv.buildExternalStorageAppDataDirs(packageName));
20401                        clearDirectory(conn.mContainerService,
20402                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20403                    }
20404                }
20405            } finally {
20406                mContext.unbindService(conn);
20407            }
20408        }
20409    }
20410
20411    @Override
20412    public void clearApplicationProfileData(String packageName) {
20413        enforceSystemOrRoot("Only the system can clear all profile data");
20414
20415        final PackageParser.Package pkg;
20416        synchronized (mPackages) {
20417            pkg = mPackages.get(packageName);
20418        }
20419
20420        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20421            synchronized (mInstallLock) {
20422                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20423            }
20424        }
20425    }
20426
20427    @Override
20428    public void clearApplicationUserData(final String packageName,
20429            final IPackageDataObserver observer, final int userId) {
20430        mContext.enforceCallingOrSelfPermission(
20431                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20432
20433        final int callingUid = Binder.getCallingUid();
20434        enforceCrossUserPermission(callingUid, userId,
20435                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20436
20437        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20438        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20439        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20440            throw new SecurityException("Cannot clear data for a protected package: "
20441                    + packageName);
20442        }
20443        // Queue up an async operation since the package deletion may take a little while.
20444        mHandler.post(new Runnable() {
20445            public void run() {
20446                mHandler.removeCallbacks(this);
20447                final boolean succeeded;
20448                if (!filterApp) {
20449                    try (PackageFreezer freezer = freezePackage(packageName,
20450                            "clearApplicationUserData")) {
20451                        synchronized (mInstallLock) {
20452                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20453                        }
20454                        clearExternalStorageDataSync(packageName, userId, true);
20455                        synchronized (mPackages) {
20456                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20457                                    packageName, userId);
20458                        }
20459                    }
20460                    if (succeeded) {
20461                        // invoke DeviceStorageMonitor's update method to clear any notifications
20462                        DeviceStorageMonitorInternal dsm = LocalServices
20463                                .getService(DeviceStorageMonitorInternal.class);
20464                        if (dsm != null) {
20465                            dsm.checkMemory();
20466                        }
20467                    }
20468                } else {
20469                    succeeded = false;
20470                }
20471                if (observer != null) {
20472                    try {
20473                        observer.onRemoveCompleted(packageName, succeeded);
20474                    } catch (RemoteException e) {
20475                        Log.i(TAG, "Observer no longer exists.");
20476                    }
20477                } //end if observer
20478            } //end run
20479        });
20480    }
20481
20482    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20483        if (packageName == null) {
20484            Slog.w(TAG, "Attempt to delete null packageName.");
20485            return false;
20486        }
20487
20488        // Try finding details about the requested package
20489        PackageParser.Package pkg;
20490        synchronized (mPackages) {
20491            pkg = mPackages.get(packageName);
20492            if (pkg == null) {
20493                final PackageSetting ps = mSettings.mPackages.get(packageName);
20494                if (ps != null) {
20495                    pkg = ps.pkg;
20496                }
20497            }
20498
20499            if (pkg == null) {
20500                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20501                return false;
20502            }
20503
20504            PackageSetting ps = (PackageSetting) pkg.mExtras;
20505            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20506        }
20507
20508        clearAppDataLIF(pkg, userId,
20509                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20510
20511        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20512        removeKeystoreDataIfNeeded(userId, appId);
20513
20514        UserManagerInternal umInternal = getUserManagerInternal();
20515        final int flags;
20516        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20517            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20518        } else if (umInternal.isUserRunning(userId)) {
20519            flags = StorageManager.FLAG_STORAGE_DE;
20520        } else {
20521            flags = 0;
20522        }
20523        prepareAppDataContentsLIF(pkg, userId, flags);
20524
20525        return true;
20526    }
20527
20528    /**
20529     * Reverts user permission state changes (permissions and flags) in
20530     * all packages for a given user.
20531     *
20532     * @param userId The device user for which to do a reset.
20533     */
20534    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20535        final int packageCount = mPackages.size();
20536        for (int i = 0; i < packageCount; i++) {
20537            PackageParser.Package pkg = mPackages.valueAt(i);
20538            PackageSetting ps = (PackageSetting) pkg.mExtras;
20539            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20540        }
20541    }
20542
20543    private void resetNetworkPolicies(int userId) {
20544        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20545    }
20546
20547    /**
20548     * Reverts user permission state changes (permissions and flags).
20549     *
20550     * @param ps The package for which to reset.
20551     * @param userId The device user for which to do a reset.
20552     */
20553    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20554            final PackageSetting ps, final int userId) {
20555        if (ps.pkg == null) {
20556            return;
20557        }
20558
20559        // These are flags that can change base on user actions.
20560        final int userSettableMask = FLAG_PERMISSION_USER_SET
20561                | FLAG_PERMISSION_USER_FIXED
20562                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20563                | FLAG_PERMISSION_REVIEW_REQUIRED;
20564
20565        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20566                | FLAG_PERMISSION_POLICY_FIXED;
20567
20568        boolean writeInstallPermissions = false;
20569        boolean writeRuntimePermissions = false;
20570
20571        final int permissionCount = ps.pkg.requestedPermissions.size();
20572        for (int i = 0; i < permissionCount; i++) {
20573            String permission = ps.pkg.requestedPermissions.get(i);
20574
20575            BasePermission bp = mSettings.mPermissions.get(permission);
20576            if (bp == null) {
20577                continue;
20578            }
20579
20580            // If shared user we just reset the state to which only this app contributed.
20581            if (ps.sharedUser != null) {
20582                boolean used = false;
20583                final int packageCount = ps.sharedUser.packages.size();
20584                for (int j = 0; j < packageCount; j++) {
20585                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20586                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20587                            && pkg.pkg.requestedPermissions.contains(permission)) {
20588                        used = true;
20589                        break;
20590                    }
20591                }
20592                if (used) {
20593                    continue;
20594                }
20595            }
20596
20597            PermissionsState permissionsState = ps.getPermissionsState();
20598
20599            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20600
20601            // Always clear the user settable flags.
20602            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20603                    bp.name) != null;
20604            // If permission review is enabled and this is a legacy app, mark the
20605            // permission as requiring a review as this is the initial state.
20606            int flags = 0;
20607            if (mPermissionReviewRequired
20608                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20609                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20610            }
20611            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20612                if (hasInstallState) {
20613                    writeInstallPermissions = true;
20614                } else {
20615                    writeRuntimePermissions = true;
20616                }
20617            }
20618
20619            // Below is only runtime permission handling.
20620            if (!bp.isRuntime()) {
20621                continue;
20622            }
20623
20624            // Never clobber system or policy.
20625            if ((oldFlags & policyOrSystemFlags) != 0) {
20626                continue;
20627            }
20628
20629            // If this permission was granted by default, make sure it is.
20630            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20631                if (permissionsState.grantRuntimePermission(bp, userId)
20632                        != PERMISSION_OPERATION_FAILURE) {
20633                    writeRuntimePermissions = true;
20634                }
20635            // If permission review is enabled the permissions for a legacy apps
20636            // are represented as constantly granted runtime ones, so don't revoke.
20637            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20638                // Otherwise, reset the permission.
20639                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20640                switch (revokeResult) {
20641                    case PERMISSION_OPERATION_SUCCESS:
20642                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20643                        writeRuntimePermissions = true;
20644                        final int appId = ps.appId;
20645                        mHandler.post(new Runnable() {
20646                            @Override
20647                            public void run() {
20648                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20649                            }
20650                        });
20651                    } break;
20652                }
20653            }
20654        }
20655
20656        // Synchronously write as we are taking permissions away.
20657        if (writeRuntimePermissions) {
20658            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20659        }
20660
20661        // Synchronously write as we are taking permissions away.
20662        if (writeInstallPermissions) {
20663            mSettings.writeLPr();
20664        }
20665    }
20666
20667    /**
20668     * Remove entries from the keystore daemon. Will only remove it if the
20669     * {@code appId} is valid.
20670     */
20671    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20672        if (appId < 0) {
20673            return;
20674        }
20675
20676        final KeyStore keyStore = KeyStore.getInstance();
20677        if (keyStore != null) {
20678            if (userId == UserHandle.USER_ALL) {
20679                for (final int individual : sUserManager.getUserIds()) {
20680                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20681                }
20682            } else {
20683                keyStore.clearUid(UserHandle.getUid(userId, appId));
20684            }
20685        } else {
20686            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20687        }
20688    }
20689
20690    @Override
20691    public void deleteApplicationCacheFiles(final String packageName,
20692            final IPackageDataObserver observer) {
20693        final int userId = UserHandle.getCallingUserId();
20694        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20695    }
20696
20697    @Override
20698    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20699            final IPackageDataObserver observer) {
20700        final int callingUid = Binder.getCallingUid();
20701        mContext.enforceCallingOrSelfPermission(
20702                android.Manifest.permission.DELETE_CACHE_FILES, null);
20703        enforceCrossUserPermission(callingUid, userId,
20704                /* requireFullPermission= */ true, /* checkShell= */ false,
20705                "delete application cache files");
20706        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20707                android.Manifest.permission.ACCESS_INSTANT_APPS);
20708
20709        final PackageParser.Package pkg;
20710        synchronized (mPackages) {
20711            pkg = mPackages.get(packageName);
20712        }
20713
20714        // Queue up an async operation since the package deletion may take a little while.
20715        mHandler.post(new Runnable() {
20716            public void run() {
20717                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20718                boolean doClearData = true;
20719                if (ps != null) {
20720                    final boolean targetIsInstantApp =
20721                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20722                    doClearData = !targetIsInstantApp
20723                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20724                }
20725                if (doClearData) {
20726                    synchronized (mInstallLock) {
20727                        final int flags = StorageManager.FLAG_STORAGE_DE
20728                                | StorageManager.FLAG_STORAGE_CE;
20729                        // We're only clearing cache files, so we don't care if the
20730                        // app is unfrozen and still able to run
20731                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20732                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20733                    }
20734                    clearExternalStorageDataSync(packageName, userId, false);
20735                }
20736                if (observer != null) {
20737                    try {
20738                        observer.onRemoveCompleted(packageName, true);
20739                    } catch (RemoteException e) {
20740                        Log.i(TAG, "Observer no longer exists.");
20741                    }
20742                }
20743            }
20744        });
20745    }
20746
20747    @Override
20748    public void getPackageSizeInfo(final String packageName, int userHandle,
20749            final IPackageStatsObserver observer) {
20750        throw new UnsupportedOperationException(
20751                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20752    }
20753
20754    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20755        final PackageSetting ps;
20756        synchronized (mPackages) {
20757            ps = mSettings.mPackages.get(packageName);
20758            if (ps == null) {
20759                Slog.w(TAG, "Failed to find settings for " + packageName);
20760                return false;
20761            }
20762        }
20763
20764        final String[] packageNames = { packageName };
20765        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20766        final String[] codePaths = { ps.codePathString };
20767
20768        try {
20769            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20770                    ps.appId, ceDataInodes, codePaths, stats);
20771
20772            // For now, ignore code size of packages on system partition
20773            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20774                stats.codeSize = 0;
20775            }
20776
20777            // External clients expect these to be tracked separately
20778            stats.dataSize -= stats.cacheSize;
20779
20780        } catch (InstallerException e) {
20781            Slog.w(TAG, String.valueOf(e));
20782            return false;
20783        }
20784
20785        return true;
20786    }
20787
20788    private int getUidTargetSdkVersionLockedLPr(int uid) {
20789        Object obj = mSettings.getUserIdLPr(uid);
20790        if (obj instanceof SharedUserSetting) {
20791            final SharedUserSetting sus = (SharedUserSetting) obj;
20792            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20793            final Iterator<PackageSetting> it = sus.packages.iterator();
20794            while (it.hasNext()) {
20795                final PackageSetting ps = it.next();
20796                if (ps.pkg != null) {
20797                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20798                    if (v < vers) vers = v;
20799                }
20800            }
20801            return vers;
20802        } else if (obj instanceof PackageSetting) {
20803            final PackageSetting ps = (PackageSetting) obj;
20804            if (ps.pkg != null) {
20805                return ps.pkg.applicationInfo.targetSdkVersion;
20806            }
20807        }
20808        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20809    }
20810
20811    @Override
20812    public void addPreferredActivity(IntentFilter filter, int match,
20813            ComponentName[] set, ComponentName activity, int userId) {
20814        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20815                "Adding preferred");
20816    }
20817
20818    private void addPreferredActivityInternal(IntentFilter filter, int match,
20819            ComponentName[] set, ComponentName activity, boolean always, int userId,
20820            String opname) {
20821        // writer
20822        int callingUid = Binder.getCallingUid();
20823        enforceCrossUserPermission(callingUid, userId,
20824                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20825        if (filter.countActions() == 0) {
20826            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20827            return;
20828        }
20829        synchronized (mPackages) {
20830            if (mContext.checkCallingOrSelfPermission(
20831                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20832                    != PackageManager.PERMISSION_GRANTED) {
20833                if (getUidTargetSdkVersionLockedLPr(callingUid)
20834                        < Build.VERSION_CODES.FROYO) {
20835                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20836                            + callingUid);
20837                    return;
20838                }
20839                mContext.enforceCallingOrSelfPermission(
20840                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20841            }
20842
20843            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20844            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20845                    + userId + ":");
20846            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20847            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20848            scheduleWritePackageRestrictionsLocked(userId);
20849            postPreferredActivityChangedBroadcast(userId);
20850        }
20851    }
20852
20853    private void postPreferredActivityChangedBroadcast(int userId) {
20854        mHandler.post(() -> {
20855            final IActivityManager am = ActivityManager.getService();
20856            if (am == null) {
20857                return;
20858            }
20859
20860            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20861            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20862            try {
20863                am.broadcastIntent(null, intent, null, null,
20864                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20865                        null, false, false, userId);
20866            } catch (RemoteException e) {
20867            }
20868        });
20869    }
20870
20871    @Override
20872    public void replacePreferredActivity(IntentFilter filter, int match,
20873            ComponentName[] set, ComponentName activity, int userId) {
20874        if (filter.countActions() != 1) {
20875            throw new IllegalArgumentException(
20876                    "replacePreferredActivity expects filter to have only 1 action.");
20877        }
20878        if (filter.countDataAuthorities() != 0
20879                || filter.countDataPaths() != 0
20880                || filter.countDataSchemes() > 1
20881                || filter.countDataTypes() != 0) {
20882            throw new IllegalArgumentException(
20883                    "replacePreferredActivity expects filter to have no data authorities, " +
20884                    "paths, or types; and at most one scheme.");
20885        }
20886
20887        final int callingUid = Binder.getCallingUid();
20888        enforceCrossUserPermission(callingUid, userId,
20889                true /* requireFullPermission */, false /* checkShell */,
20890                "replace preferred activity");
20891        synchronized (mPackages) {
20892            if (mContext.checkCallingOrSelfPermission(
20893                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20894                    != PackageManager.PERMISSION_GRANTED) {
20895                if (getUidTargetSdkVersionLockedLPr(callingUid)
20896                        < Build.VERSION_CODES.FROYO) {
20897                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20898                            + Binder.getCallingUid());
20899                    return;
20900                }
20901                mContext.enforceCallingOrSelfPermission(
20902                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20903            }
20904
20905            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20906            if (pir != null) {
20907                // Get all of the existing entries that exactly match this filter.
20908                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20909                if (existing != null && existing.size() == 1) {
20910                    PreferredActivity cur = existing.get(0);
20911                    if (DEBUG_PREFERRED) {
20912                        Slog.i(TAG, "Checking replace of preferred:");
20913                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20914                        if (!cur.mPref.mAlways) {
20915                            Slog.i(TAG, "  -- CUR; not mAlways!");
20916                        } else {
20917                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20918                            Slog.i(TAG, "  -- CUR: mSet="
20919                                    + Arrays.toString(cur.mPref.mSetComponents));
20920                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20921                            Slog.i(TAG, "  -- NEW: mMatch="
20922                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20923                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20924                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20925                        }
20926                    }
20927                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20928                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20929                            && cur.mPref.sameSet(set)) {
20930                        // Setting the preferred activity to what it happens to be already
20931                        if (DEBUG_PREFERRED) {
20932                            Slog.i(TAG, "Replacing with same preferred activity "
20933                                    + cur.mPref.mShortComponent + " for user "
20934                                    + userId + ":");
20935                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20936                        }
20937                        return;
20938                    }
20939                }
20940
20941                if (existing != null) {
20942                    if (DEBUG_PREFERRED) {
20943                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20944                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20945                    }
20946                    for (int i = 0; i < existing.size(); i++) {
20947                        PreferredActivity pa = existing.get(i);
20948                        if (DEBUG_PREFERRED) {
20949                            Slog.i(TAG, "Removing existing preferred activity "
20950                                    + pa.mPref.mComponent + ":");
20951                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20952                        }
20953                        pir.removeFilter(pa);
20954                    }
20955                }
20956            }
20957            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20958                    "Replacing preferred");
20959        }
20960    }
20961
20962    @Override
20963    public void clearPackagePreferredActivities(String packageName) {
20964        final int callingUid = Binder.getCallingUid();
20965        if (getInstantAppPackageName(callingUid) != null) {
20966            return;
20967        }
20968        // writer
20969        synchronized (mPackages) {
20970            PackageParser.Package pkg = mPackages.get(packageName);
20971            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20972                if (mContext.checkCallingOrSelfPermission(
20973                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20974                        != PackageManager.PERMISSION_GRANTED) {
20975                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20976                            < Build.VERSION_CODES.FROYO) {
20977                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20978                                + callingUid);
20979                        return;
20980                    }
20981                    mContext.enforceCallingOrSelfPermission(
20982                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20983                }
20984            }
20985            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20986            if (ps != null
20987                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20988                return;
20989            }
20990            int user = UserHandle.getCallingUserId();
20991            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20992                scheduleWritePackageRestrictionsLocked(user);
20993            }
20994        }
20995    }
20996
20997    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20998    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20999        ArrayList<PreferredActivity> removed = null;
21000        boolean changed = false;
21001        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21002            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
21003            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21004            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
21005                continue;
21006            }
21007            Iterator<PreferredActivity> it = pir.filterIterator();
21008            while (it.hasNext()) {
21009                PreferredActivity pa = it.next();
21010                // Mark entry for removal only if it matches the package name
21011                // and the entry is of type "always".
21012                if (packageName == null ||
21013                        (pa.mPref.mComponent.getPackageName().equals(packageName)
21014                                && pa.mPref.mAlways)) {
21015                    if (removed == null) {
21016                        removed = new ArrayList<PreferredActivity>();
21017                    }
21018                    removed.add(pa);
21019                }
21020            }
21021            if (removed != null) {
21022                for (int j=0; j<removed.size(); j++) {
21023                    PreferredActivity pa = removed.get(j);
21024                    pir.removeFilter(pa);
21025                }
21026                changed = true;
21027            }
21028        }
21029        if (changed) {
21030            postPreferredActivityChangedBroadcast(userId);
21031        }
21032        return changed;
21033    }
21034
21035    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21036    private void clearIntentFilterVerificationsLPw(int userId) {
21037        final int packageCount = mPackages.size();
21038        for (int i = 0; i < packageCount; i++) {
21039            PackageParser.Package pkg = mPackages.valueAt(i);
21040            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
21041        }
21042    }
21043
21044    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21045    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
21046        if (userId == UserHandle.USER_ALL) {
21047            if (mSettings.removeIntentFilterVerificationLPw(packageName,
21048                    sUserManager.getUserIds())) {
21049                for (int oneUserId : sUserManager.getUserIds()) {
21050                    scheduleWritePackageRestrictionsLocked(oneUserId);
21051                }
21052            }
21053        } else {
21054            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
21055                scheduleWritePackageRestrictionsLocked(userId);
21056            }
21057        }
21058    }
21059
21060    /** Clears state for all users, and touches intent filter verification policy */
21061    void clearDefaultBrowserIfNeeded(String packageName) {
21062        for (int oneUserId : sUserManager.getUserIds()) {
21063            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
21064        }
21065    }
21066
21067    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
21068        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
21069        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
21070            if (packageName.equals(defaultBrowserPackageName)) {
21071                setDefaultBrowserPackageName(null, userId);
21072            }
21073        }
21074    }
21075
21076    @Override
21077    public void resetApplicationPreferences(int userId) {
21078        mContext.enforceCallingOrSelfPermission(
21079                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
21080        final long identity = Binder.clearCallingIdentity();
21081        // writer
21082        try {
21083            synchronized (mPackages) {
21084                clearPackagePreferredActivitiesLPw(null, userId);
21085                mSettings.applyDefaultPreferredAppsLPw(this, userId);
21086                // TODO: We have to reset the default SMS and Phone. This requires
21087                // significant refactoring to keep all default apps in the package
21088                // manager (cleaner but more work) or have the services provide
21089                // callbacks to the package manager to request a default app reset.
21090                applyFactoryDefaultBrowserLPw(userId);
21091                clearIntentFilterVerificationsLPw(userId);
21092                primeDomainVerificationsLPw(userId);
21093                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
21094                scheduleWritePackageRestrictionsLocked(userId);
21095            }
21096            resetNetworkPolicies(userId);
21097        } finally {
21098            Binder.restoreCallingIdentity(identity);
21099        }
21100    }
21101
21102    @Override
21103    public int getPreferredActivities(List<IntentFilter> outFilters,
21104            List<ComponentName> outActivities, String packageName) {
21105        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21106            return 0;
21107        }
21108        int num = 0;
21109        final int userId = UserHandle.getCallingUserId();
21110        // reader
21111        synchronized (mPackages) {
21112            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
21113            if (pir != null) {
21114                final Iterator<PreferredActivity> it = pir.filterIterator();
21115                while (it.hasNext()) {
21116                    final PreferredActivity pa = it.next();
21117                    if (packageName == null
21118                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
21119                                    && pa.mPref.mAlways)) {
21120                        if (outFilters != null) {
21121                            outFilters.add(new IntentFilter(pa));
21122                        }
21123                        if (outActivities != null) {
21124                            outActivities.add(pa.mPref.mComponent);
21125                        }
21126                    }
21127                }
21128            }
21129        }
21130
21131        return num;
21132    }
21133
21134    @Override
21135    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
21136            int userId) {
21137        int callingUid = Binder.getCallingUid();
21138        if (callingUid != Process.SYSTEM_UID) {
21139            throw new SecurityException(
21140                    "addPersistentPreferredActivity can only be run by the system");
21141        }
21142        if (filter.countActions() == 0) {
21143            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
21144            return;
21145        }
21146        synchronized (mPackages) {
21147            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
21148                    ":");
21149            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
21150            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
21151                    new PersistentPreferredActivity(filter, activity));
21152            scheduleWritePackageRestrictionsLocked(userId);
21153            postPreferredActivityChangedBroadcast(userId);
21154        }
21155    }
21156
21157    @Override
21158    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
21159        int callingUid = Binder.getCallingUid();
21160        if (callingUid != Process.SYSTEM_UID) {
21161            throw new SecurityException(
21162                    "clearPackagePersistentPreferredActivities can only be run by the system");
21163        }
21164        ArrayList<PersistentPreferredActivity> removed = null;
21165        boolean changed = false;
21166        synchronized (mPackages) {
21167            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21168                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21169                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21170                        .valueAt(i);
21171                if (userId != thisUserId) {
21172                    continue;
21173                }
21174                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21175                while (it.hasNext()) {
21176                    PersistentPreferredActivity ppa = it.next();
21177                    // Mark entry for removal only if it matches the package name.
21178                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21179                        if (removed == null) {
21180                            removed = new ArrayList<PersistentPreferredActivity>();
21181                        }
21182                        removed.add(ppa);
21183                    }
21184                }
21185                if (removed != null) {
21186                    for (int j=0; j<removed.size(); j++) {
21187                        PersistentPreferredActivity ppa = removed.get(j);
21188                        ppir.removeFilter(ppa);
21189                    }
21190                    changed = true;
21191                }
21192            }
21193
21194            if (changed) {
21195                scheduleWritePackageRestrictionsLocked(userId);
21196                postPreferredActivityChangedBroadcast(userId);
21197            }
21198        }
21199    }
21200
21201    /**
21202     * Common machinery for picking apart a restored XML blob and passing
21203     * it to a caller-supplied functor to be applied to the running system.
21204     */
21205    private void restoreFromXml(XmlPullParser parser, int userId,
21206            String expectedStartTag, BlobXmlRestorer functor)
21207            throws IOException, XmlPullParserException {
21208        int type;
21209        while ((type = parser.next()) != XmlPullParser.START_TAG
21210                && type != XmlPullParser.END_DOCUMENT) {
21211        }
21212        if (type != XmlPullParser.START_TAG) {
21213            // oops didn't find a start tag?!
21214            if (DEBUG_BACKUP) {
21215                Slog.e(TAG, "Didn't find start tag during restore");
21216            }
21217            return;
21218        }
21219Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21220        // this is supposed to be TAG_PREFERRED_BACKUP
21221        if (!expectedStartTag.equals(parser.getName())) {
21222            if (DEBUG_BACKUP) {
21223                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21224            }
21225            return;
21226        }
21227
21228        // skip interfering stuff, then we're aligned with the backing implementation
21229        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21230Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21231        functor.apply(parser, userId);
21232    }
21233
21234    private interface BlobXmlRestorer {
21235        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21236    }
21237
21238    /**
21239     * Non-Binder method, support for the backup/restore mechanism: write the
21240     * full set of preferred activities in its canonical XML format.  Returns the
21241     * XML output as a byte array, or null if there is none.
21242     */
21243    @Override
21244    public byte[] getPreferredActivityBackup(int userId) {
21245        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21246            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21247        }
21248
21249        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21250        try {
21251            final XmlSerializer serializer = new FastXmlSerializer();
21252            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21253            serializer.startDocument(null, true);
21254            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21255
21256            synchronized (mPackages) {
21257                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21258            }
21259
21260            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21261            serializer.endDocument();
21262            serializer.flush();
21263        } catch (Exception e) {
21264            if (DEBUG_BACKUP) {
21265                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21266            }
21267            return null;
21268        }
21269
21270        return dataStream.toByteArray();
21271    }
21272
21273    @Override
21274    public void restorePreferredActivities(byte[] backup, int userId) {
21275        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21276            throw new SecurityException("Only the system may call restorePreferredActivities()");
21277        }
21278
21279        try {
21280            final XmlPullParser parser = Xml.newPullParser();
21281            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21282            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21283                    new BlobXmlRestorer() {
21284                        @Override
21285                        public void apply(XmlPullParser parser, int userId)
21286                                throws XmlPullParserException, IOException {
21287                            synchronized (mPackages) {
21288                                mSettings.readPreferredActivitiesLPw(parser, userId);
21289                            }
21290                        }
21291                    } );
21292        } catch (Exception e) {
21293            if (DEBUG_BACKUP) {
21294                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21295            }
21296        }
21297    }
21298
21299    /**
21300     * Non-Binder method, support for the backup/restore mechanism: write the
21301     * default browser (etc) settings in its canonical XML format.  Returns the default
21302     * browser XML representation as a byte array, or null if there is none.
21303     */
21304    @Override
21305    public byte[] getDefaultAppsBackup(int userId) {
21306        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21307            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21308        }
21309
21310        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21311        try {
21312            final XmlSerializer serializer = new FastXmlSerializer();
21313            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21314            serializer.startDocument(null, true);
21315            serializer.startTag(null, TAG_DEFAULT_APPS);
21316
21317            synchronized (mPackages) {
21318                mSettings.writeDefaultAppsLPr(serializer, userId);
21319            }
21320
21321            serializer.endTag(null, TAG_DEFAULT_APPS);
21322            serializer.endDocument();
21323            serializer.flush();
21324        } catch (Exception e) {
21325            if (DEBUG_BACKUP) {
21326                Slog.e(TAG, "Unable to write default apps for backup", e);
21327            }
21328            return null;
21329        }
21330
21331        return dataStream.toByteArray();
21332    }
21333
21334    @Override
21335    public void restoreDefaultApps(byte[] backup, int userId) {
21336        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21337            throw new SecurityException("Only the system may call restoreDefaultApps()");
21338        }
21339
21340        try {
21341            final XmlPullParser parser = Xml.newPullParser();
21342            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21343            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21344                    new BlobXmlRestorer() {
21345                        @Override
21346                        public void apply(XmlPullParser parser, int userId)
21347                                throws XmlPullParserException, IOException {
21348                            synchronized (mPackages) {
21349                                mSettings.readDefaultAppsLPw(parser, userId);
21350                            }
21351                        }
21352                    } );
21353        } catch (Exception e) {
21354            if (DEBUG_BACKUP) {
21355                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21356            }
21357        }
21358    }
21359
21360    @Override
21361    public byte[] getIntentFilterVerificationBackup(int userId) {
21362        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21363            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21364        }
21365
21366        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21367        try {
21368            final XmlSerializer serializer = new FastXmlSerializer();
21369            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21370            serializer.startDocument(null, true);
21371            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21372
21373            synchronized (mPackages) {
21374                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21375            }
21376
21377            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21378            serializer.endDocument();
21379            serializer.flush();
21380        } catch (Exception e) {
21381            if (DEBUG_BACKUP) {
21382                Slog.e(TAG, "Unable to write default apps for backup", e);
21383            }
21384            return null;
21385        }
21386
21387        return dataStream.toByteArray();
21388    }
21389
21390    @Override
21391    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21392        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21393            throw new SecurityException("Only the system may call restorePreferredActivities()");
21394        }
21395
21396        try {
21397            final XmlPullParser parser = Xml.newPullParser();
21398            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21399            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21400                    new BlobXmlRestorer() {
21401                        @Override
21402                        public void apply(XmlPullParser parser, int userId)
21403                                throws XmlPullParserException, IOException {
21404                            synchronized (mPackages) {
21405                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21406                                mSettings.writeLPr();
21407                            }
21408                        }
21409                    } );
21410        } catch (Exception e) {
21411            if (DEBUG_BACKUP) {
21412                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21413            }
21414        }
21415    }
21416
21417    @Override
21418    public byte[] getPermissionGrantBackup(int userId) {
21419        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21420            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21421        }
21422
21423        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21424        try {
21425            final XmlSerializer serializer = new FastXmlSerializer();
21426            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21427            serializer.startDocument(null, true);
21428            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21429
21430            synchronized (mPackages) {
21431                serializeRuntimePermissionGrantsLPr(serializer, userId);
21432            }
21433
21434            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21435            serializer.endDocument();
21436            serializer.flush();
21437        } catch (Exception e) {
21438            if (DEBUG_BACKUP) {
21439                Slog.e(TAG, "Unable to write default apps for backup", e);
21440            }
21441            return null;
21442        }
21443
21444        return dataStream.toByteArray();
21445    }
21446
21447    @Override
21448    public void restorePermissionGrants(byte[] backup, int userId) {
21449        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21450            throw new SecurityException("Only the system may call restorePermissionGrants()");
21451        }
21452
21453        try {
21454            final XmlPullParser parser = Xml.newPullParser();
21455            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21456            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21457                    new BlobXmlRestorer() {
21458                        @Override
21459                        public void apply(XmlPullParser parser, int userId)
21460                                throws XmlPullParserException, IOException {
21461                            synchronized (mPackages) {
21462                                processRestoredPermissionGrantsLPr(parser, userId);
21463                            }
21464                        }
21465                    } );
21466        } catch (Exception e) {
21467            if (DEBUG_BACKUP) {
21468                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21469            }
21470        }
21471    }
21472
21473    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21474            throws IOException {
21475        serializer.startTag(null, TAG_ALL_GRANTS);
21476
21477        final int N = mSettings.mPackages.size();
21478        for (int i = 0; i < N; i++) {
21479            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21480            boolean pkgGrantsKnown = false;
21481
21482            PermissionsState packagePerms = ps.getPermissionsState();
21483
21484            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21485                final int grantFlags = state.getFlags();
21486                // only look at grants that are not system/policy fixed
21487                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21488                    final boolean isGranted = state.isGranted();
21489                    // And only back up the user-twiddled state bits
21490                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21491                        final String packageName = mSettings.mPackages.keyAt(i);
21492                        if (!pkgGrantsKnown) {
21493                            serializer.startTag(null, TAG_GRANT);
21494                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21495                            pkgGrantsKnown = true;
21496                        }
21497
21498                        final boolean userSet =
21499                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21500                        final boolean userFixed =
21501                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21502                        final boolean revoke =
21503                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21504
21505                        serializer.startTag(null, TAG_PERMISSION);
21506                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21507                        if (isGranted) {
21508                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21509                        }
21510                        if (userSet) {
21511                            serializer.attribute(null, ATTR_USER_SET, "true");
21512                        }
21513                        if (userFixed) {
21514                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21515                        }
21516                        if (revoke) {
21517                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21518                        }
21519                        serializer.endTag(null, TAG_PERMISSION);
21520                    }
21521                }
21522            }
21523
21524            if (pkgGrantsKnown) {
21525                serializer.endTag(null, TAG_GRANT);
21526            }
21527        }
21528
21529        serializer.endTag(null, TAG_ALL_GRANTS);
21530    }
21531
21532    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21533            throws XmlPullParserException, IOException {
21534        String pkgName = null;
21535        int outerDepth = parser.getDepth();
21536        int type;
21537        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21538                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21539            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21540                continue;
21541            }
21542
21543            final String tagName = parser.getName();
21544            if (tagName.equals(TAG_GRANT)) {
21545                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21546                if (DEBUG_BACKUP) {
21547                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21548                }
21549            } else if (tagName.equals(TAG_PERMISSION)) {
21550
21551                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21552                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21553
21554                int newFlagSet = 0;
21555                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21556                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21557                }
21558                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21559                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21560                }
21561                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21562                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21563                }
21564                if (DEBUG_BACKUP) {
21565                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21566                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21567                }
21568                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21569                if (ps != null) {
21570                    // Already installed so we apply the grant immediately
21571                    if (DEBUG_BACKUP) {
21572                        Slog.v(TAG, "        + already installed; applying");
21573                    }
21574                    PermissionsState perms = ps.getPermissionsState();
21575                    BasePermission bp = mSettings.mPermissions.get(permName);
21576                    if (bp != null) {
21577                        if (isGranted) {
21578                            perms.grantRuntimePermission(bp, userId);
21579                        }
21580                        if (newFlagSet != 0) {
21581                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21582                        }
21583                    }
21584                } else {
21585                    // Need to wait for post-restore install to apply the grant
21586                    if (DEBUG_BACKUP) {
21587                        Slog.v(TAG, "        - not yet installed; saving for later");
21588                    }
21589                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21590                            isGranted, newFlagSet, userId);
21591                }
21592            } else {
21593                PackageManagerService.reportSettingsProblem(Log.WARN,
21594                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21595                XmlUtils.skipCurrentTag(parser);
21596            }
21597        }
21598
21599        scheduleWriteSettingsLocked();
21600        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21601    }
21602
21603    @Override
21604    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21605            int sourceUserId, int targetUserId, int flags) {
21606        mContext.enforceCallingOrSelfPermission(
21607                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21608        int callingUid = Binder.getCallingUid();
21609        enforceOwnerRights(ownerPackage, callingUid);
21610        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21611        if (intentFilter.countActions() == 0) {
21612            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21613            return;
21614        }
21615        synchronized (mPackages) {
21616            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21617                    ownerPackage, targetUserId, flags);
21618            CrossProfileIntentResolver resolver =
21619                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21620            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21621            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21622            if (existing != null) {
21623                int size = existing.size();
21624                for (int i = 0; i < size; i++) {
21625                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21626                        return;
21627                    }
21628                }
21629            }
21630            resolver.addFilter(newFilter);
21631            scheduleWritePackageRestrictionsLocked(sourceUserId);
21632        }
21633    }
21634
21635    @Override
21636    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21637        mContext.enforceCallingOrSelfPermission(
21638                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21639        final int callingUid = Binder.getCallingUid();
21640        enforceOwnerRights(ownerPackage, callingUid);
21641        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21642        synchronized (mPackages) {
21643            CrossProfileIntentResolver resolver =
21644                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21645            ArraySet<CrossProfileIntentFilter> set =
21646                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21647            for (CrossProfileIntentFilter filter : set) {
21648                if (filter.getOwnerPackage().equals(ownerPackage)) {
21649                    resolver.removeFilter(filter);
21650                }
21651            }
21652            scheduleWritePackageRestrictionsLocked(sourceUserId);
21653        }
21654    }
21655
21656    // Enforcing that callingUid is owning pkg on userId
21657    private void enforceOwnerRights(String pkg, int callingUid) {
21658        // The system owns everything.
21659        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21660            return;
21661        }
21662        final int callingUserId = UserHandle.getUserId(callingUid);
21663        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21664        if (pi == null) {
21665            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21666                    + callingUserId);
21667        }
21668        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21669            throw new SecurityException("Calling uid " + callingUid
21670                    + " does not own package " + pkg);
21671        }
21672    }
21673
21674    @Override
21675    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21676        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21677            return null;
21678        }
21679        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21680    }
21681
21682    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21683        UserManagerService ums = UserManagerService.getInstance();
21684        if (ums != null) {
21685            final UserInfo parent = ums.getProfileParent(userId);
21686            final int launcherUid = (parent != null) ? parent.id : userId;
21687            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21688            if (launcherComponent != null) {
21689                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21690                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21691                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21692                        .setPackage(launcherComponent.getPackageName());
21693                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21694            }
21695        }
21696    }
21697
21698    /**
21699     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21700     * then reports the most likely home activity or null if there are more than one.
21701     */
21702    private ComponentName getDefaultHomeActivity(int userId) {
21703        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21704        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21705        if (cn != null) {
21706            return cn;
21707        }
21708
21709        // Find the launcher with the highest priority and return that component if there are no
21710        // other home activity with the same priority.
21711        int lastPriority = Integer.MIN_VALUE;
21712        ComponentName lastComponent = null;
21713        final int size = allHomeCandidates.size();
21714        for (int i = 0; i < size; i++) {
21715            final ResolveInfo ri = allHomeCandidates.get(i);
21716            if (ri.priority > lastPriority) {
21717                lastComponent = ri.activityInfo.getComponentName();
21718                lastPriority = ri.priority;
21719            } else if (ri.priority == lastPriority) {
21720                // Two components found with same priority.
21721                lastComponent = null;
21722            }
21723        }
21724        return lastComponent;
21725    }
21726
21727    private Intent getHomeIntent() {
21728        Intent intent = new Intent(Intent.ACTION_MAIN);
21729        intent.addCategory(Intent.CATEGORY_HOME);
21730        intent.addCategory(Intent.CATEGORY_DEFAULT);
21731        return intent;
21732    }
21733
21734    private IntentFilter getHomeFilter() {
21735        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21736        filter.addCategory(Intent.CATEGORY_HOME);
21737        filter.addCategory(Intent.CATEGORY_DEFAULT);
21738        return filter;
21739    }
21740
21741    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21742            int userId) {
21743        Intent intent  = getHomeIntent();
21744        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21745                PackageManager.GET_META_DATA, userId);
21746        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21747                true, false, false, userId);
21748
21749        allHomeCandidates.clear();
21750        if (list != null) {
21751            for (ResolveInfo ri : list) {
21752                allHomeCandidates.add(ri);
21753            }
21754        }
21755        return (preferred == null || preferred.activityInfo == null)
21756                ? null
21757                : new ComponentName(preferred.activityInfo.packageName,
21758                        preferred.activityInfo.name);
21759    }
21760
21761    @Override
21762    public void setHomeActivity(ComponentName comp, int userId) {
21763        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21764            return;
21765        }
21766        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21767        getHomeActivitiesAsUser(homeActivities, userId);
21768
21769        boolean found = false;
21770
21771        final int size = homeActivities.size();
21772        final ComponentName[] set = new ComponentName[size];
21773        for (int i = 0; i < size; i++) {
21774            final ResolveInfo candidate = homeActivities.get(i);
21775            final ActivityInfo info = candidate.activityInfo;
21776            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21777            set[i] = activityName;
21778            if (!found && activityName.equals(comp)) {
21779                found = true;
21780            }
21781        }
21782        if (!found) {
21783            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21784                    + userId);
21785        }
21786        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21787                set, comp, userId);
21788    }
21789
21790    private @Nullable String getSetupWizardPackageName() {
21791        final Intent intent = new Intent(Intent.ACTION_MAIN);
21792        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21793
21794        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21795                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21796                        | MATCH_DISABLED_COMPONENTS,
21797                UserHandle.myUserId());
21798        if (matches.size() == 1) {
21799            return matches.get(0).getComponentInfo().packageName;
21800        } else {
21801            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21802                    + ": matches=" + matches);
21803            return null;
21804        }
21805    }
21806
21807    private @Nullable String getStorageManagerPackageName() {
21808        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21809
21810        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21811                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21812                        | MATCH_DISABLED_COMPONENTS,
21813                UserHandle.myUserId());
21814        if (matches.size() == 1) {
21815            return matches.get(0).getComponentInfo().packageName;
21816        } else {
21817            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21818                    + matches.size() + ": matches=" + matches);
21819            return null;
21820        }
21821    }
21822
21823    @Override
21824    public void setApplicationEnabledSetting(String appPackageName,
21825            int newState, int flags, int userId, String callingPackage) {
21826        if (!sUserManager.exists(userId)) return;
21827        if (callingPackage == null) {
21828            callingPackage = Integer.toString(Binder.getCallingUid());
21829        }
21830        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21831    }
21832
21833    @Override
21834    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21835        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21836        synchronized (mPackages) {
21837            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21838            if (pkgSetting != null) {
21839                pkgSetting.setUpdateAvailable(updateAvailable);
21840            }
21841        }
21842    }
21843
21844    @Override
21845    public void setComponentEnabledSetting(ComponentName componentName,
21846            int newState, int flags, int userId) {
21847        if (!sUserManager.exists(userId)) return;
21848        setEnabledSetting(componentName.getPackageName(),
21849                componentName.getClassName(), newState, flags, userId, null);
21850    }
21851
21852    private void setEnabledSetting(final String packageName, String className, int newState,
21853            final int flags, int userId, String callingPackage) {
21854        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21855              || newState == COMPONENT_ENABLED_STATE_ENABLED
21856              || newState == COMPONENT_ENABLED_STATE_DISABLED
21857              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21858              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21859            throw new IllegalArgumentException("Invalid new component state: "
21860                    + newState);
21861        }
21862        PackageSetting pkgSetting;
21863        final int callingUid = Binder.getCallingUid();
21864        final int permission;
21865        if (callingUid == Process.SYSTEM_UID) {
21866            permission = PackageManager.PERMISSION_GRANTED;
21867        } else {
21868            permission = mContext.checkCallingOrSelfPermission(
21869                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21870        }
21871        enforceCrossUserPermission(callingUid, userId,
21872                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21873        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21874        boolean sendNow = false;
21875        boolean isApp = (className == null);
21876        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21877        String componentName = isApp ? packageName : className;
21878        int packageUid = -1;
21879        ArrayList<String> components;
21880
21881        // reader
21882        synchronized (mPackages) {
21883            pkgSetting = mSettings.mPackages.get(packageName);
21884            if (pkgSetting == null) {
21885                if (!isCallerInstantApp) {
21886                    if (className == null) {
21887                        throw new IllegalArgumentException("Unknown package: " + packageName);
21888                    }
21889                    throw new IllegalArgumentException(
21890                            "Unknown component: " + packageName + "/" + className);
21891                } else {
21892                    // throw SecurityException to prevent leaking package information
21893                    throw new SecurityException(
21894                            "Attempt to change component state; "
21895                            + "pid=" + Binder.getCallingPid()
21896                            + ", uid=" + callingUid
21897                            + (className == null
21898                                    ? ", package=" + packageName
21899                                    : ", component=" + packageName + "/" + className));
21900                }
21901            }
21902        }
21903
21904        // Limit who can change which apps
21905        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21906            // Don't allow apps that don't have permission to modify other apps
21907            if (!allowedByPermission
21908                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21909                throw new SecurityException(
21910                        "Attempt to change component state; "
21911                        + "pid=" + Binder.getCallingPid()
21912                        + ", uid=" + callingUid
21913                        + (className == null
21914                                ? ", package=" + packageName
21915                                : ", component=" + packageName + "/" + className));
21916            }
21917            // Don't allow changing protected packages.
21918            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21919                throw new SecurityException("Cannot disable a protected package: " + packageName);
21920            }
21921        }
21922
21923        synchronized (mPackages) {
21924            if (callingUid == Process.SHELL_UID
21925                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21926                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21927                // unless it is a test package.
21928                int oldState = pkgSetting.getEnabled(userId);
21929                if (className == null
21930                        &&
21931                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21932                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21933                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21934                        &&
21935                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21936                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21937                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21938                    // ok
21939                } else {
21940                    throw new SecurityException(
21941                            "Shell cannot change component state for " + packageName + "/"
21942                                    + className + " to " + newState);
21943                }
21944            }
21945        }
21946        if (className == null) {
21947            // We're dealing with an application/package level state change
21948            synchronized (mPackages) {
21949                if (pkgSetting.getEnabled(userId) == newState) {
21950                    // Nothing to do
21951                    return;
21952                }
21953            }
21954            // If we're enabling a system stub, there's a little more work to do.
21955            // Prior to enabling the package, we need to decompress the APK(s) to the
21956            // data partition and then replace the version on the system partition.
21957            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21958            final boolean isSystemStub = deletedPkg.isStub
21959                    && deletedPkg.isSystemApp();
21960            if (isSystemStub
21961                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21962                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21963                final File codePath = decompressPackage(deletedPkg);
21964                if (codePath == null) {
21965                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21966                    return;
21967                }
21968                // TODO remove direct parsing of the package object during internal cleanup
21969                // of scan package
21970                // We need to call parse directly here for no other reason than we need
21971                // the new package in order to disable the old one [we use the information
21972                // for some internal optimization to optionally create a new package setting
21973                // object on replace]. However, we can't get the package from the scan
21974                // because the scan modifies live structures and we need to remove the
21975                // old [system] package from the system before a scan can be attempted.
21976                // Once scan is indempotent we can remove this parse and use the package
21977                // object we scanned, prior to adding it to package settings.
21978                final PackageParser pp = new PackageParser();
21979                pp.setSeparateProcesses(mSeparateProcesses);
21980                pp.setDisplayMetrics(mMetrics);
21981                pp.setCallback(mPackageParserCallback);
21982                final PackageParser.Package tmpPkg;
21983                try {
21984                    final int parseFlags = mDefParseFlags
21985                            | PackageParser.PARSE_MUST_BE_APK
21986                            | PackageParser.PARSE_IS_SYSTEM
21987                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21988                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21989                } catch (PackageParserException e) {
21990                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21991                    return;
21992                }
21993                synchronized (mInstallLock) {
21994                    // Disable the stub and remove any package entries
21995                    removePackageLI(deletedPkg, true);
21996                    synchronized (mPackages) {
21997                        disableSystemPackageLPw(deletedPkg, tmpPkg);
21998                    }
21999                    final PackageParser.Package newPkg;
22000                    try (PackageFreezer freezer =
22001                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
22002                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
22003                                | PackageParser.PARSE_ENFORCE_CODE;
22004                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
22005                                0 /*currentTime*/, null /*user*/);
22006                        prepareAppDataAfterInstallLIF(newPkg);
22007                        synchronized (mPackages) {
22008                            try {
22009                                updateSharedLibrariesLPr(newPkg, null);
22010                            } catch (PackageManagerException e) {
22011                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
22012                            }
22013                            updatePermissionsLPw(newPkg.packageName, newPkg,
22014                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
22015                            mSettings.writeLPr();
22016                        }
22017                    } catch (PackageManagerException e) {
22018                        // Whoops! Something went wrong; try to roll back to the stub
22019                        Slog.w(TAG, "Failed to install compressed system package:"
22020                                + pkgSetting.name, e);
22021                        // Remove the failed install
22022                        removeCodePathLI(codePath);
22023
22024                        // Install the system package
22025                        try (PackageFreezer freezer =
22026                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
22027                            synchronized (mPackages) {
22028                                // NOTE: The system package always needs to be enabled; even
22029                                // if it's for a compressed stub. If we don't, installing the
22030                                // system package fails during scan [scanning checks the disabled
22031                                // packages]. We will reverse this later, after we've "installed"
22032                                // the stub.
22033                                // This leaves us in a fragile state; the stub should never be
22034                                // enabled, so, cross your fingers and hope nothing goes wrong
22035                                // until we can disable the package later.
22036                                enableSystemPackageLPw(deletedPkg);
22037                            }
22038                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
22039                                    false /*isPrivileged*/, null /*allUserHandles*/,
22040                                    null /*origUserHandles*/, null /*origPermissionsState*/,
22041                                    true /*writeSettings*/);
22042                        } catch (PackageManagerException pme) {
22043                            Slog.w(TAG, "Failed to restore system package:"
22044                                    + deletedPkg.packageName, pme);
22045                        } finally {
22046                            synchronized (mPackages) {
22047                                mSettings.disableSystemPackageLPw(
22048                                        deletedPkg.packageName, true /*replaced*/);
22049                                mSettings.writeLPr();
22050                            }
22051                        }
22052                        return;
22053                    }
22054                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
22055                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22056                    mDexManager.notifyPackageUpdated(newPkg.packageName,
22057                            newPkg.baseCodePath, newPkg.splitCodePaths);
22058                }
22059            }
22060            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
22061                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
22062                // Don't care about who enables an app.
22063                callingPackage = null;
22064            }
22065            synchronized (mPackages) {
22066                pkgSetting.setEnabled(newState, userId, callingPackage);
22067            }
22068        } else {
22069            synchronized (mPackages) {
22070                // We're dealing with a component level state change
22071                // First, verify that this is a valid class name.
22072                PackageParser.Package pkg = pkgSetting.pkg;
22073                if (pkg == null || !pkg.hasComponentClassName(className)) {
22074                    if (pkg != null &&
22075                            pkg.applicationInfo.targetSdkVersion >=
22076                                    Build.VERSION_CODES.JELLY_BEAN) {
22077                        throw new IllegalArgumentException("Component class " + className
22078                                + " does not exist in " + packageName);
22079                    } else {
22080                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
22081                                + className + " does not exist in " + packageName);
22082                    }
22083                }
22084                switch (newState) {
22085                    case COMPONENT_ENABLED_STATE_ENABLED:
22086                        if (!pkgSetting.enableComponentLPw(className, userId)) {
22087                            return;
22088                        }
22089                        break;
22090                    case COMPONENT_ENABLED_STATE_DISABLED:
22091                        if (!pkgSetting.disableComponentLPw(className, userId)) {
22092                            return;
22093                        }
22094                        break;
22095                    case COMPONENT_ENABLED_STATE_DEFAULT:
22096                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
22097                            return;
22098                        }
22099                        break;
22100                    default:
22101                        Slog.e(TAG, "Invalid new component state: " + newState);
22102                        return;
22103                }
22104            }
22105        }
22106        synchronized (mPackages) {
22107            scheduleWritePackageRestrictionsLocked(userId);
22108            updateSequenceNumberLP(pkgSetting, new int[] { userId });
22109            final long callingId = Binder.clearCallingIdentity();
22110            try {
22111                updateInstantAppInstallerLocked(packageName);
22112            } finally {
22113                Binder.restoreCallingIdentity(callingId);
22114            }
22115            components = mPendingBroadcasts.get(userId, packageName);
22116            final boolean newPackage = components == null;
22117            if (newPackage) {
22118                components = new ArrayList<String>();
22119            }
22120            if (!components.contains(componentName)) {
22121                components.add(componentName);
22122            }
22123            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
22124                sendNow = true;
22125                // Purge entry from pending broadcast list if another one exists already
22126                // since we are sending one right away.
22127                mPendingBroadcasts.remove(userId, packageName);
22128            } else {
22129                if (newPackage) {
22130                    mPendingBroadcasts.put(userId, packageName, components);
22131                }
22132                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
22133                    // Schedule a message
22134                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
22135                }
22136            }
22137        }
22138
22139        long callingId = Binder.clearCallingIdentity();
22140        try {
22141            if (sendNow) {
22142                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
22143                sendPackageChangedBroadcast(packageName,
22144                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
22145            }
22146        } finally {
22147            Binder.restoreCallingIdentity(callingId);
22148        }
22149    }
22150
22151    @Override
22152    public void flushPackageRestrictionsAsUser(int userId) {
22153        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22154            return;
22155        }
22156        if (!sUserManager.exists(userId)) {
22157            return;
22158        }
22159        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
22160                false /* checkShell */, "flushPackageRestrictions");
22161        synchronized (mPackages) {
22162            mSettings.writePackageRestrictionsLPr(userId);
22163            mDirtyUsers.remove(userId);
22164            if (mDirtyUsers.isEmpty()) {
22165                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
22166            }
22167        }
22168    }
22169
22170    private void sendPackageChangedBroadcast(String packageName,
22171            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
22172        if (DEBUG_INSTALL)
22173            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
22174                    + componentNames);
22175        Bundle extras = new Bundle(4);
22176        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
22177        String nameList[] = new String[componentNames.size()];
22178        componentNames.toArray(nameList);
22179        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
22180        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
22181        extras.putInt(Intent.EXTRA_UID, packageUid);
22182        // If this is not reporting a change of the overall package, then only send it
22183        // to registered receivers.  We don't want to launch a swath of apps for every
22184        // little component state change.
22185        final int flags = !componentNames.contains(packageName)
22186                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
22187        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
22188                new int[] {UserHandle.getUserId(packageUid)});
22189    }
22190
22191    @Override
22192    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
22193        if (!sUserManager.exists(userId)) return;
22194        final int callingUid = Binder.getCallingUid();
22195        if (getInstantAppPackageName(callingUid) != null) {
22196            return;
22197        }
22198        final int permission = mContext.checkCallingOrSelfPermission(
22199                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
22200        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
22201        enforceCrossUserPermission(callingUid, userId,
22202                true /* requireFullPermission */, true /* checkShell */, "stop package");
22203        // writer
22204        synchronized (mPackages) {
22205            final PackageSetting ps = mSettings.mPackages.get(packageName);
22206            if (!filterAppAccessLPr(ps, callingUid, userId)
22207                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
22208                            allowedByPermission, callingUid, userId)) {
22209                scheduleWritePackageRestrictionsLocked(userId);
22210            }
22211        }
22212    }
22213
22214    @Override
22215    public String getInstallerPackageName(String packageName) {
22216        final int callingUid = Binder.getCallingUid();
22217        if (getInstantAppPackageName(callingUid) != null) {
22218            return null;
22219        }
22220        // reader
22221        synchronized (mPackages) {
22222            final PackageSetting ps = mSettings.mPackages.get(packageName);
22223            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
22224                return null;
22225            }
22226            return mSettings.getInstallerPackageNameLPr(packageName);
22227        }
22228    }
22229
22230    public boolean isOrphaned(String packageName) {
22231        // reader
22232        synchronized (mPackages) {
22233            return mSettings.isOrphaned(packageName);
22234        }
22235    }
22236
22237    @Override
22238    public int getApplicationEnabledSetting(String packageName, int userId) {
22239        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22240        int callingUid = Binder.getCallingUid();
22241        enforceCrossUserPermission(callingUid, userId,
22242                false /* requireFullPermission */, false /* checkShell */, "get enabled");
22243        // reader
22244        synchronized (mPackages) {
22245            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22246                return COMPONENT_ENABLED_STATE_DISABLED;
22247            }
22248            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22249        }
22250    }
22251
22252    @Override
22253    public int getComponentEnabledSetting(ComponentName component, int userId) {
22254        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22255        int callingUid = Binder.getCallingUid();
22256        enforceCrossUserPermission(callingUid, userId,
22257                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22258        synchronized (mPackages) {
22259            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22260                    component, TYPE_UNKNOWN, userId)) {
22261                return COMPONENT_ENABLED_STATE_DISABLED;
22262            }
22263            return mSettings.getComponentEnabledSettingLPr(component, userId);
22264        }
22265    }
22266
22267    @Override
22268    public void enterSafeMode() {
22269        enforceSystemOrRoot("Only the system can request entering safe mode");
22270
22271        if (!mSystemReady) {
22272            mSafeMode = true;
22273        }
22274    }
22275
22276    @Override
22277    public void systemReady() {
22278        enforceSystemOrRoot("Only the system can claim the system is ready");
22279
22280        mSystemReady = true;
22281        final ContentResolver resolver = mContext.getContentResolver();
22282        ContentObserver co = new ContentObserver(mHandler) {
22283            @Override
22284            public void onChange(boolean selfChange) {
22285                mEphemeralAppsDisabled =
22286                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22287                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22288            }
22289        };
22290        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22291                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22292                false, co, UserHandle.USER_SYSTEM);
22293        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22294                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22295        co.onChange(true);
22296
22297        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22298        // disabled after already being started.
22299        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22300                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22301
22302        // Read the compatibilty setting when the system is ready.
22303        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22304                mContext.getContentResolver(),
22305                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22306        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22307        if (DEBUG_SETTINGS) {
22308            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22309        }
22310
22311        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22312
22313        synchronized (mPackages) {
22314            // Verify that all of the preferred activity components actually
22315            // exist.  It is possible for applications to be updated and at
22316            // that point remove a previously declared activity component that
22317            // had been set as a preferred activity.  We try to clean this up
22318            // the next time we encounter that preferred activity, but it is
22319            // possible for the user flow to never be able to return to that
22320            // situation so here we do a sanity check to make sure we haven't
22321            // left any junk around.
22322            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22323            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22324                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22325                removed.clear();
22326                for (PreferredActivity pa : pir.filterSet()) {
22327                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22328                        removed.add(pa);
22329                    }
22330                }
22331                if (removed.size() > 0) {
22332                    for (int r=0; r<removed.size(); r++) {
22333                        PreferredActivity pa = removed.get(r);
22334                        Slog.w(TAG, "Removing dangling preferred activity: "
22335                                + pa.mPref.mComponent);
22336                        pir.removeFilter(pa);
22337                    }
22338                    mSettings.writePackageRestrictionsLPr(
22339                            mSettings.mPreferredActivities.keyAt(i));
22340                }
22341            }
22342
22343            for (int userId : UserManagerService.getInstance().getUserIds()) {
22344                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22345                    grantPermissionsUserIds = ArrayUtils.appendInt(
22346                            grantPermissionsUserIds, userId);
22347                }
22348            }
22349        }
22350        sUserManager.systemReady();
22351
22352        // If we upgraded grant all default permissions before kicking off.
22353        for (int userId : grantPermissionsUserIds) {
22354            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22355        }
22356
22357        // If we did not grant default permissions, we preload from this the
22358        // default permission exceptions lazily to ensure we don't hit the
22359        // disk on a new user creation.
22360        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22361            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22362        }
22363
22364        // Kick off any messages waiting for system ready
22365        if (mPostSystemReadyMessages != null) {
22366            for (Message msg : mPostSystemReadyMessages) {
22367                msg.sendToTarget();
22368            }
22369            mPostSystemReadyMessages = null;
22370        }
22371
22372        // Watch for external volumes that come and go over time
22373        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22374        storage.registerListener(mStorageListener);
22375
22376        mInstallerService.systemReady();
22377        mPackageDexOptimizer.systemReady();
22378
22379        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22380                StorageManagerInternal.class);
22381        StorageManagerInternal.addExternalStoragePolicy(
22382                new StorageManagerInternal.ExternalStorageMountPolicy() {
22383            @Override
22384            public int getMountMode(int uid, String packageName) {
22385                if (Process.isIsolated(uid)) {
22386                    return Zygote.MOUNT_EXTERNAL_NONE;
22387                }
22388                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22389                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22390                }
22391                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22392                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22393                }
22394                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22395                    return Zygote.MOUNT_EXTERNAL_READ;
22396                }
22397                return Zygote.MOUNT_EXTERNAL_WRITE;
22398            }
22399
22400            @Override
22401            public boolean hasExternalStorage(int uid, String packageName) {
22402                return true;
22403            }
22404        });
22405
22406        // Now that we're mostly running, clean up stale users and apps
22407        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22408        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22409
22410        if (mPrivappPermissionsViolations != null) {
22411            Slog.wtf(TAG,"Signature|privileged permissions not in "
22412                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22413            mPrivappPermissionsViolations = null;
22414        }
22415    }
22416
22417    public void waitForAppDataPrepared() {
22418        if (mPrepareAppDataFuture == null) {
22419            return;
22420        }
22421        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22422        mPrepareAppDataFuture = null;
22423    }
22424
22425    @Override
22426    public boolean isSafeMode() {
22427        // allow instant applications
22428        return mSafeMode;
22429    }
22430
22431    @Override
22432    public boolean hasSystemUidErrors() {
22433        // allow instant applications
22434        return mHasSystemUidErrors;
22435    }
22436
22437    static String arrayToString(int[] array) {
22438        StringBuffer buf = new StringBuffer(128);
22439        buf.append('[');
22440        if (array != null) {
22441            for (int i=0; i<array.length; i++) {
22442                if (i > 0) buf.append(", ");
22443                buf.append(array[i]);
22444            }
22445        }
22446        buf.append(']');
22447        return buf.toString();
22448    }
22449
22450    static class DumpState {
22451        public static final int DUMP_LIBS = 1 << 0;
22452        public static final int DUMP_FEATURES = 1 << 1;
22453        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22454        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22455        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22456        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22457        public static final int DUMP_PERMISSIONS = 1 << 6;
22458        public static final int DUMP_PACKAGES = 1 << 7;
22459        public static final int DUMP_SHARED_USERS = 1 << 8;
22460        public static final int DUMP_MESSAGES = 1 << 9;
22461        public static final int DUMP_PROVIDERS = 1 << 10;
22462        public static final int DUMP_VERIFIERS = 1 << 11;
22463        public static final int DUMP_PREFERRED = 1 << 12;
22464        public static final int DUMP_PREFERRED_XML = 1 << 13;
22465        public static final int DUMP_KEYSETS = 1 << 14;
22466        public static final int DUMP_VERSION = 1 << 15;
22467        public static final int DUMP_INSTALLS = 1 << 16;
22468        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22469        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22470        public static final int DUMP_FROZEN = 1 << 19;
22471        public static final int DUMP_DEXOPT = 1 << 20;
22472        public static final int DUMP_COMPILER_STATS = 1 << 21;
22473        public static final int DUMP_CHANGES = 1 << 22;
22474        public static final int DUMP_VOLUMES = 1 << 23;
22475
22476        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22477
22478        private int mTypes;
22479
22480        private int mOptions;
22481
22482        private boolean mTitlePrinted;
22483
22484        private SharedUserSetting mSharedUser;
22485
22486        public boolean isDumping(int type) {
22487            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22488                return true;
22489            }
22490
22491            return (mTypes & type) != 0;
22492        }
22493
22494        public void setDump(int type) {
22495            mTypes |= type;
22496        }
22497
22498        public boolean isOptionEnabled(int option) {
22499            return (mOptions & option) != 0;
22500        }
22501
22502        public void setOptionEnabled(int option) {
22503            mOptions |= option;
22504        }
22505
22506        public boolean onTitlePrinted() {
22507            final boolean printed = mTitlePrinted;
22508            mTitlePrinted = true;
22509            return printed;
22510        }
22511
22512        public boolean getTitlePrinted() {
22513            return mTitlePrinted;
22514        }
22515
22516        public void setTitlePrinted(boolean enabled) {
22517            mTitlePrinted = enabled;
22518        }
22519
22520        public SharedUserSetting getSharedUser() {
22521            return mSharedUser;
22522        }
22523
22524        public void setSharedUser(SharedUserSetting user) {
22525            mSharedUser = user;
22526        }
22527    }
22528
22529    @Override
22530    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22531            FileDescriptor err, String[] args, ShellCallback callback,
22532            ResultReceiver resultReceiver) {
22533        (new PackageManagerShellCommand(this)).exec(
22534                this, in, out, err, args, callback, resultReceiver);
22535    }
22536
22537    @Override
22538    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22539        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22540
22541        DumpState dumpState = new DumpState();
22542        boolean fullPreferred = false;
22543        boolean checkin = false;
22544
22545        String packageName = null;
22546        ArraySet<String> permissionNames = null;
22547
22548        int opti = 0;
22549        while (opti < args.length) {
22550            String opt = args[opti];
22551            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22552                break;
22553            }
22554            opti++;
22555
22556            if ("-a".equals(opt)) {
22557                // Right now we only know how to print all.
22558            } else if ("-h".equals(opt)) {
22559                pw.println("Package manager dump options:");
22560                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22561                pw.println("    --checkin: dump for a checkin");
22562                pw.println("    -f: print details of intent filters");
22563                pw.println("    -h: print this help");
22564                pw.println("  cmd may be one of:");
22565                pw.println("    l[ibraries]: list known shared libraries");
22566                pw.println("    f[eatures]: list device features");
22567                pw.println("    k[eysets]: print known keysets");
22568                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22569                pw.println("    perm[issions]: dump permissions");
22570                pw.println("    permission [name ...]: dump declaration and use of given permission");
22571                pw.println("    pref[erred]: print preferred package settings");
22572                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22573                pw.println("    prov[iders]: dump content providers");
22574                pw.println("    p[ackages]: dump installed packages");
22575                pw.println("    s[hared-users]: dump shared user IDs");
22576                pw.println("    m[essages]: print collected runtime messages");
22577                pw.println("    v[erifiers]: print package verifier info");
22578                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22579                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22580                pw.println("    version: print database version info");
22581                pw.println("    write: write current settings now");
22582                pw.println("    installs: details about install sessions");
22583                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22584                pw.println("    dexopt: dump dexopt state");
22585                pw.println("    compiler-stats: dump compiler statistics");
22586                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22587                pw.println("    <package.name>: info about given package");
22588                return;
22589            } else if ("--checkin".equals(opt)) {
22590                checkin = true;
22591            } else if ("-f".equals(opt)) {
22592                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22593            } else if ("--proto".equals(opt)) {
22594                dumpProto(fd);
22595                return;
22596            } else {
22597                pw.println("Unknown argument: " + opt + "; use -h for help");
22598            }
22599        }
22600
22601        // Is the caller requesting to dump a particular piece of data?
22602        if (opti < args.length) {
22603            String cmd = args[opti];
22604            opti++;
22605            // Is this a package name?
22606            if ("android".equals(cmd) || cmd.contains(".")) {
22607                packageName = cmd;
22608                // When dumping a single package, we always dump all of its
22609                // filter information since the amount of data will be reasonable.
22610                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22611            } else if ("check-permission".equals(cmd)) {
22612                if (opti >= args.length) {
22613                    pw.println("Error: check-permission missing permission argument");
22614                    return;
22615                }
22616                String perm = args[opti];
22617                opti++;
22618                if (opti >= args.length) {
22619                    pw.println("Error: check-permission missing package argument");
22620                    return;
22621                }
22622
22623                String pkg = args[opti];
22624                opti++;
22625                int user = UserHandle.getUserId(Binder.getCallingUid());
22626                if (opti < args.length) {
22627                    try {
22628                        user = Integer.parseInt(args[opti]);
22629                    } catch (NumberFormatException e) {
22630                        pw.println("Error: check-permission user argument is not a number: "
22631                                + args[opti]);
22632                        return;
22633                    }
22634                }
22635
22636                // Normalize package name to handle renamed packages and static libs
22637                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22638
22639                pw.println(checkPermission(perm, pkg, user));
22640                return;
22641            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22642                dumpState.setDump(DumpState.DUMP_LIBS);
22643            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22644                dumpState.setDump(DumpState.DUMP_FEATURES);
22645            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22646                if (opti >= args.length) {
22647                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22648                            | DumpState.DUMP_SERVICE_RESOLVERS
22649                            | DumpState.DUMP_RECEIVER_RESOLVERS
22650                            | DumpState.DUMP_CONTENT_RESOLVERS);
22651                } else {
22652                    while (opti < args.length) {
22653                        String name = args[opti];
22654                        if ("a".equals(name) || "activity".equals(name)) {
22655                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22656                        } else if ("s".equals(name) || "service".equals(name)) {
22657                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22658                        } else if ("r".equals(name) || "receiver".equals(name)) {
22659                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22660                        } else if ("c".equals(name) || "content".equals(name)) {
22661                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22662                        } else {
22663                            pw.println("Error: unknown resolver table type: " + name);
22664                            return;
22665                        }
22666                        opti++;
22667                    }
22668                }
22669            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22670                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22671            } else if ("permission".equals(cmd)) {
22672                if (opti >= args.length) {
22673                    pw.println("Error: permission requires permission name");
22674                    return;
22675                }
22676                permissionNames = new ArraySet<>();
22677                while (opti < args.length) {
22678                    permissionNames.add(args[opti]);
22679                    opti++;
22680                }
22681                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22682                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22683            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22684                dumpState.setDump(DumpState.DUMP_PREFERRED);
22685            } else if ("preferred-xml".equals(cmd)) {
22686                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22687                if (opti < args.length && "--full".equals(args[opti])) {
22688                    fullPreferred = true;
22689                    opti++;
22690                }
22691            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22692                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22693            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22694                dumpState.setDump(DumpState.DUMP_PACKAGES);
22695            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22696                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22697            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22698                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22699            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22700                dumpState.setDump(DumpState.DUMP_MESSAGES);
22701            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22702                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22703            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22704                    || "intent-filter-verifiers".equals(cmd)) {
22705                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22706            } else if ("version".equals(cmd)) {
22707                dumpState.setDump(DumpState.DUMP_VERSION);
22708            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22709                dumpState.setDump(DumpState.DUMP_KEYSETS);
22710            } else if ("installs".equals(cmd)) {
22711                dumpState.setDump(DumpState.DUMP_INSTALLS);
22712            } else if ("frozen".equals(cmd)) {
22713                dumpState.setDump(DumpState.DUMP_FROZEN);
22714            } else if ("volumes".equals(cmd)) {
22715                dumpState.setDump(DumpState.DUMP_VOLUMES);
22716            } else if ("dexopt".equals(cmd)) {
22717                dumpState.setDump(DumpState.DUMP_DEXOPT);
22718            } else if ("compiler-stats".equals(cmd)) {
22719                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22720            } else if ("changes".equals(cmd)) {
22721                dumpState.setDump(DumpState.DUMP_CHANGES);
22722            } else if ("write".equals(cmd)) {
22723                synchronized (mPackages) {
22724                    mSettings.writeLPr();
22725                    pw.println("Settings written.");
22726                    return;
22727                }
22728            }
22729        }
22730
22731        if (checkin) {
22732            pw.println("vers,1");
22733        }
22734
22735        // reader
22736        synchronized (mPackages) {
22737            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22738                if (!checkin) {
22739                    if (dumpState.onTitlePrinted())
22740                        pw.println();
22741                    pw.println("Database versions:");
22742                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22743                }
22744            }
22745
22746            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22747                if (!checkin) {
22748                    if (dumpState.onTitlePrinted())
22749                        pw.println();
22750                    pw.println("Verifiers:");
22751                    pw.print("  Required: ");
22752                    pw.print(mRequiredVerifierPackage);
22753                    pw.print(" (uid=");
22754                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22755                            UserHandle.USER_SYSTEM));
22756                    pw.println(")");
22757                } else if (mRequiredVerifierPackage != null) {
22758                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22759                    pw.print(",");
22760                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22761                            UserHandle.USER_SYSTEM));
22762                }
22763            }
22764
22765            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22766                    packageName == null) {
22767                if (mIntentFilterVerifierComponent != null) {
22768                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22769                    if (!checkin) {
22770                        if (dumpState.onTitlePrinted())
22771                            pw.println();
22772                        pw.println("Intent Filter Verifier:");
22773                        pw.print("  Using: ");
22774                        pw.print(verifierPackageName);
22775                        pw.print(" (uid=");
22776                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22777                                UserHandle.USER_SYSTEM));
22778                        pw.println(")");
22779                    } else if (verifierPackageName != null) {
22780                        pw.print("ifv,"); pw.print(verifierPackageName);
22781                        pw.print(",");
22782                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22783                                UserHandle.USER_SYSTEM));
22784                    }
22785                } else {
22786                    pw.println();
22787                    pw.println("No Intent Filter Verifier available!");
22788                }
22789            }
22790
22791            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22792                boolean printedHeader = false;
22793                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22794                while (it.hasNext()) {
22795                    String libName = it.next();
22796                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22797                    if (versionedLib == null) {
22798                        continue;
22799                    }
22800                    final int versionCount = versionedLib.size();
22801                    for (int i = 0; i < versionCount; i++) {
22802                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22803                        if (!checkin) {
22804                            if (!printedHeader) {
22805                                if (dumpState.onTitlePrinted())
22806                                    pw.println();
22807                                pw.println("Libraries:");
22808                                printedHeader = true;
22809                            }
22810                            pw.print("  ");
22811                        } else {
22812                            pw.print("lib,");
22813                        }
22814                        pw.print(libEntry.info.getName());
22815                        if (libEntry.info.isStatic()) {
22816                            pw.print(" version=" + libEntry.info.getVersion());
22817                        }
22818                        if (!checkin) {
22819                            pw.print(" -> ");
22820                        }
22821                        if (libEntry.path != null) {
22822                            pw.print(" (jar) ");
22823                            pw.print(libEntry.path);
22824                        } else {
22825                            pw.print(" (apk) ");
22826                            pw.print(libEntry.apk);
22827                        }
22828                        pw.println();
22829                    }
22830                }
22831            }
22832
22833            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22834                if (dumpState.onTitlePrinted())
22835                    pw.println();
22836                if (!checkin) {
22837                    pw.println("Features:");
22838                }
22839
22840                synchronized (mAvailableFeatures) {
22841                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22842                        if (checkin) {
22843                            pw.print("feat,");
22844                            pw.print(feat.name);
22845                            pw.print(",");
22846                            pw.println(feat.version);
22847                        } else {
22848                            pw.print("  ");
22849                            pw.print(feat.name);
22850                            if (feat.version > 0) {
22851                                pw.print(" version=");
22852                                pw.print(feat.version);
22853                            }
22854                            pw.println();
22855                        }
22856                    }
22857                }
22858            }
22859
22860            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22861                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22862                        : "Activity Resolver Table:", "  ", packageName,
22863                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22864                    dumpState.setTitlePrinted(true);
22865                }
22866            }
22867            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22868                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22869                        : "Receiver Resolver Table:", "  ", packageName,
22870                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22871                    dumpState.setTitlePrinted(true);
22872                }
22873            }
22874            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22875                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22876                        : "Service Resolver Table:", "  ", packageName,
22877                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22878                    dumpState.setTitlePrinted(true);
22879                }
22880            }
22881            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22882                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22883                        : "Provider Resolver Table:", "  ", packageName,
22884                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22885                    dumpState.setTitlePrinted(true);
22886                }
22887            }
22888
22889            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22890                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22891                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22892                    int user = mSettings.mPreferredActivities.keyAt(i);
22893                    if (pir.dump(pw,
22894                            dumpState.getTitlePrinted()
22895                                ? "\nPreferred Activities User " + user + ":"
22896                                : "Preferred Activities User " + user + ":", "  ",
22897                            packageName, true, false)) {
22898                        dumpState.setTitlePrinted(true);
22899                    }
22900                }
22901            }
22902
22903            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22904                pw.flush();
22905                FileOutputStream fout = new FileOutputStream(fd);
22906                BufferedOutputStream str = new BufferedOutputStream(fout);
22907                XmlSerializer serializer = new FastXmlSerializer();
22908                try {
22909                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22910                    serializer.startDocument(null, true);
22911                    serializer.setFeature(
22912                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22913                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22914                    serializer.endDocument();
22915                    serializer.flush();
22916                } catch (IllegalArgumentException e) {
22917                    pw.println("Failed writing: " + e);
22918                } catch (IllegalStateException e) {
22919                    pw.println("Failed writing: " + e);
22920                } catch (IOException e) {
22921                    pw.println("Failed writing: " + e);
22922                }
22923            }
22924
22925            if (!checkin
22926                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22927                    && packageName == null) {
22928                pw.println();
22929                int count = mSettings.mPackages.size();
22930                if (count == 0) {
22931                    pw.println("No applications!");
22932                    pw.println();
22933                } else {
22934                    final String prefix = "  ";
22935                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22936                    if (allPackageSettings.size() == 0) {
22937                        pw.println("No domain preferred apps!");
22938                        pw.println();
22939                    } else {
22940                        pw.println("App verification status:");
22941                        pw.println();
22942                        count = 0;
22943                        for (PackageSetting ps : allPackageSettings) {
22944                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22945                            if (ivi == null || ivi.getPackageName() == null) continue;
22946                            pw.println(prefix + "Package: " + ivi.getPackageName());
22947                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22948                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22949                            pw.println();
22950                            count++;
22951                        }
22952                        if (count == 0) {
22953                            pw.println(prefix + "No app verification established.");
22954                            pw.println();
22955                        }
22956                        for (int userId : sUserManager.getUserIds()) {
22957                            pw.println("App linkages for user " + userId + ":");
22958                            pw.println();
22959                            count = 0;
22960                            for (PackageSetting ps : allPackageSettings) {
22961                                final long status = ps.getDomainVerificationStatusForUser(userId);
22962                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22963                                        && !DEBUG_DOMAIN_VERIFICATION) {
22964                                    continue;
22965                                }
22966                                pw.println(prefix + "Package: " + ps.name);
22967                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22968                                String statusStr = IntentFilterVerificationInfo.
22969                                        getStatusStringFromValue(status);
22970                                pw.println(prefix + "Status:  " + statusStr);
22971                                pw.println();
22972                                count++;
22973                            }
22974                            if (count == 0) {
22975                                pw.println(prefix + "No configured app linkages.");
22976                                pw.println();
22977                            }
22978                        }
22979                    }
22980                }
22981            }
22982
22983            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22984                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22985                if (packageName == null && permissionNames == null) {
22986                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22987                        if (iperm == 0) {
22988                            if (dumpState.onTitlePrinted())
22989                                pw.println();
22990                            pw.println("AppOp Permissions:");
22991                        }
22992                        pw.print("  AppOp Permission ");
22993                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22994                        pw.println(":");
22995                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22996                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22997                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22998                        }
22999                    }
23000                }
23001            }
23002
23003            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
23004                boolean printedSomething = false;
23005                for (PackageParser.Provider p : mProviders.mProviders.values()) {
23006                    if (packageName != null && !packageName.equals(p.info.packageName)) {
23007                        continue;
23008                    }
23009                    if (!printedSomething) {
23010                        if (dumpState.onTitlePrinted())
23011                            pw.println();
23012                        pw.println("Registered ContentProviders:");
23013                        printedSomething = true;
23014                    }
23015                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
23016                    pw.print("    "); pw.println(p.toString());
23017                }
23018                printedSomething = false;
23019                for (Map.Entry<String, PackageParser.Provider> entry :
23020                        mProvidersByAuthority.entrySet()) {
23021                    PackageParser.Provider p = entry.getValue();
23022                    if (packageName != null && !packageName.equals(p.info.packageName)) {
23023                        continue;
23024                    }
23025                    if (!printedSomething) {
23026                        if (dumpState.onTitlePrinted())
23027                            pw.println();
23028                        pw.println("ContentProvider Authorities:");
23029                        printedSomething = true;
23030                    }
23031                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
23032                    pw.print("    "); pw.println(p.toString());
23033                    if (p.info != null && p.info.applicationInfo != null) {
23034                        final String appInfo = p.info.applicationInfo.toString();
23035                        pw.print("      applicationInfo="); pw.println(appInfo);
23036                    }
23037                }
23038            }
23039
23040            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
23041                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
23042            }
23043
23044            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
23045                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
23046            }
23047
23048            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
23049                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
23050            }
23051
23052            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
23053                if (dumpState.onTitlePrinted()) pw.println();
23054                pw.println("Package Changes:");
23055                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
23056                final int K = mChangedPackages.size();
23057                for (int i = 0; i < K; i++) {
23058                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
23059                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
23060                    final int N = changes.size();
23061                    if (N == 0) {
23062                        pw.print("    "); pw.println("No packages changed");
23063                    } else {
23064                        for (int j = 0; j < N; j++) {
23065                            final String pkgName = changes.valueAt(j);
23066                            final int sequenceNumber = changes.keyAt(j);
23067                            pw.print("    ");
23068                            pw.print("seq=");
23069                            pw.print(sequenceNumber);
23070                            pw.print(", package=");
23071                            pw.println(pkgName);
23072                        }
23073                    }
23074                }
23075            }
23076
23077            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
23078                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
23079            }
23080
23081            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
23082                // XXX should handle packageName != null by dumping only install data that
23083                // the given package is involved with.
23084                if (dumpState.onTitlePrinted()) pw.println();
23085
23086                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23087                ipw.println();
23088                ipw.println("Frozen packages:");
23089                ipw.increaseIndent();
23090                if (mFrozenPackages.size() == 0) {
23091                    ipw.println("(none)");
23092                } else {
23093                    for (int i = 0; i < mFrozenPackages.size(); i++) {
23094                        ipw.println(mFrozenPackages.valueAt(i));
23095                    }
23096                }
23097                ipw.decreaseIndent();
23098            }
23099
23100            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
23101                if (dumpState.onTitlePrinted()) pw.println();
23102
23103                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23104                ipw.println();
23105                ipw.println("Loaded volumes:");
23106                ipw.increaseIndent();
23107                if (mLoadedVolumes.size() == 0) {
23108                    ipw.println("(none)");
23109                } else {
23110                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
23111                        ipw.println(mLoadedVolumes.valueAt(i));
23112                    }
23113                }
23114                ipw.decreaseIndent();
23115            }
23116
23117            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
23118                if (dumpState.onTitlePrinted()) pw.println();
23119                dumpDexoptStateLPr(pw, packageName);
23120            }
23121
23122            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
23123                if (dumpState.onTitlePrinted()) pw.println();
23124                dumpCompilerStatsLPr(pw, packageName);
23125            }
23126
23127            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
23128                if (dumpState.onTitlePrinted()) pw.println();
23129                mSettings.dumpReadMessagesLPr(pw, dumpState);
23130
23131                pw.println();
23132                pw.println("Package warning messages:");
23133                BufferedReader in = null;
23134                String line = null;
23135                try {
23136                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23137                    while ((line = in.readLine()) != null) {
23138                        if (line.contains("ignored: updated version")) continue;
23139                        pw.println(line);
23140                    }
23141                } catch (IOException ignored) {
23142                } finally {
23143                    IoUtils.closeQuietly(in);
23144                }
23145            }
23146
23147            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
23148                BufferedReader in = null;
23149                String line = null;
23150                try {
23151                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23152                    while ((line = in.readLine()) != null) {
23153                        if (line.contains("ignored: updated version")) continue;
23154                        pw.print("msg,");
23155                        pw.println(line);
23156                    }
23157                } catch (IOException ignored) {
23158                } finally {
23159                    IoUtils.closeQuietly(in);
23160                }
23161            }
23162        }
23163
23164        // PackageInstaller should be called outside of mPackages lock
23165        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
23166            // XXX should handle packageName != null by dumping only install data that
23167            // the given package is involved with.
23168            if (dumpState.onTitlePrinted()) pw.println();
23169            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
23170        }
23171    }
23172
23173    private void dumpProto(FileDescriptor fd) {
23174        final ProtoOutputStream proto = new ProtoOutputStream(fd);
23175
23176        synchronized (mPackages) {
23177            final long requiredVerifierPackageToken =
23178                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
23179            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
23180            proto.write(
23181                    PackageServiceDumpProto.PackageShortProto.UID,
23182                    getPackageUid(
23183                            mRequiredVerifierPackage,
23184                            MATCH_DEBUG_TRIAGED_MISSING,
23185                            UserHandle.USER_SYSTEM));
23186            proto.end(requiredVerifierPackageToken);
23187
23188            if (mIntentFilterVerifierComponent != null) {
23189                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
23190                final long verifierPackageToken =
23191                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
23192                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
23193                proto.write(
23194                        PackageServiceDumpProto.PackageShortProto.UID,
23195                        getPackageUid(
23196                                verifierPackageName,
23197                                MATCH_DEBUG_TRIAGED_MISSING,
23198                                UserHandle.USER_SYSTEM));
23199                proto.end(verifierPackageToken);
23200            }
23201
23202            dumpSharedLibrariesProto(proto);
23203            dumpFeaturesProto(proto);
23204            mSettings.dumpPackagesProto(proto);
23205            mSettings.dumpSharedUsersProto(proto);
23206            dumpMessagesProto(proto);
23207        }
23208        proto.flush();
23209    }
23210
23211    private void dumpMessagesProto(ProtoOutputStream proto) {
23212        BufferedReader in = null;
23213        String line = null;
23214        try {
23215            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23216            while ((line = in.readLine()) != null) {
23217                if (line.contains("ignored: updated version")) continue;
23218                proto.write(PackageServiceDumpProto.MESSAGES, line);
23219            }
23220        } catch (IOException ignored) {
23221        } finally {
23222            IoUtils.closeQuietly(in);
23223        }
23224    }
23225
23226    private void dumpFeaturesProto(ProtoOutputStream proto) {
23227        synchronized (mAvailableFeatures) {
23228            final int count = mAvailableFeatures.size();
23229            for (int i = 0; i < count; i++) {
23230                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
23231                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
23232                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
23233                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
23234                proto.end(featureToken);
23235            }
23236        }
23237    }
23238
23239    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
23240        final int count = mSharedLibraries.size();
23241        for (int i = 0; i < count; i++) {
23242            final String libName = mSharedLibraries.keyAt(i);
23243            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
23244            if (versionedLib == null) {
23245                continue;
23246            }
23247            final int versionCount = versionedLib.size();
23248            for (int j = 0; j < versionCount; j++) {
23249                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23250                final long sharedLibraryToken =
23251                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23252                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23253                final boolean isJar = (libEntry.path != null);
23254                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23255                if (isJar) {
23256                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23257                } else {
23258                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23259                }
23260                proto.end(sharedLibraryToken);
23261            }
23262        }
23263    }
23264
23265    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23266        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23267        ipw.println();
23268        ipw.println("Dexopt state:");
23269        ipw.increaseIndent();
23270        Collection<PackageParser.Package> packages = null;
23271        if (packageName != null) {
23272            PackageParser.Package targetPackage = mPackages.get(packageName);
23273            if (targetPackage != null) {
23274                packages = Collections.singletonList(targetPackage);
23275            } else {
23276                ipw.println("Unable to find package: " + packageName);
23277                return;
23278            }
23279        } else {
23280            packages = mPackages.values();
23281        }
23282
23283        for (PackageParser.Package pkg : packages) {
23284            ipw.println("[" + pkg.packageName + "]");
23285            ipw.increaseIndent();
23286            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23287                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23288            ipw.decreaseIndent();
23289        }
23290    }
23291
23292    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23293        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23294        ipw.println();
23295        ipw.println("Compiler stats:");
23296        ipw.increaseIndent();
23297        Collection<PackageParser.Package> packages = null;
23298        if (packageName != null) {
23299            PackageParser.Package targetPackage = mPackages.get(packageName);
23300            if (targetPackage != null) {
23301                packages = Collections.singletonList(targetPackage);
23302            } else {
23303                ipw.println("Unable to find package: " + packageName);
23304                return;
23305            }
23306        } else {
23307            packages = mPackages.values();
23308        }
23309
23310        for (PackageParser.Package pkg : packages) {
23311            ipw.println("[" + pkg.packageName + "]");
23312            ipw.increaseIndent();
23313
23314            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23315            if (stats == null) {
23316                ipw.println("(No recorded stats)");
23317            } else {
23318                stats.dump(ipw);
23319            }
23320            ipw.decreaseIndent();
23321        }
23322    }
23323
23324    private String dumpDomainString(String packageName) {
23325        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23326                .getList();
23327        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23328
23329        ArraySet<String> result = new ArraySet<>();
23330        if (iviList.size() > 0) {
23331            for (IntentFilterVerificationInfo ivi : iviList) {
23332                for (String host : ivi.getDomains()) {
23333                    result.add(host);
23334                }
23335            }
23336        }
23337        if (filters != null && filters.size() > 0) {
23338            for (IntentFilter filter : filters) {
23339                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23340                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23341                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23342                    result.addAll(filter.getHostsList());
23343                }
23344            }
23345        }
23346
23347        StringBuilder sb = new StringBuilder(result.size() * 16);
23348        for (String domain : result) {
23349            if (sb.length() > 0) sb.append(" ");
23350            sb.append(domain);
23351        }
23352        return sb.toString();
23353    }
23354
23355    // ------- apps on sdcard specific code -------
23356    static final boolean DEBUG_SD_INSTALL = false;
23357
23358    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23359
23360    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23361
23362    private boolean mMediaMounted = false;
23363
23364    static String getEncryptKey() {
23365        try {
23366            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23367                    SD_ENCRYPTION_KEYSTORE_NAME);
23368            if (sdEncKey == null) {
23369                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23370                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23371                if (sdEncKey == null) {
23372                    Slog.e(TAG, "Failed to create encryption keys");
23373                    return null;
23374                }
23375            }
23376            return sdEncKey;
23377        } catch (NoSuchAlgorithmException nsae) {
23378            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23379            return null;
23380        } catch (IOException ioe) {
23381            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23382            return null;
23383        }
23384    }
23385
23386    /*
23387     * Update media status on PackageManager.
23388     */
23389    @Override
23390    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23391        enforceSystemOrRoot("Media status can only be updated by the system");
23392        // reader; this apparently protects mMediaMounted, but should probably
23393        // be a different lock in that case.
23394        synchronized (mPackages) {
23395            Log.i(TAG, "Updating external media status from "
23396                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23397                    + (mediaStatus ? "mounted" : "unmounted"));
23398            if (DEBUG_SD_INSTALL)
23399                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23400                        + ", mMediaMounted=" + mMediaMounted);
23401            if (mediaStatus == mMediaMounted) {
23402                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23403                        : 0, -1);
23404                mHandler.sendMessage(msg);
23405                return;
23406            }
23407            mMediaMounted = mediaStatus;
23408        }
23409        // Queue up an async operation since the package installation may take a
23410        // little while.
23411        mHandler.post(new Runnable() {
23412            public void run() {
23413                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23414            }
23415        });
23416    }
23417
23418    /**
23419     * Called by StorageManagerService when the initial ASECs to scan are available.
23420     * Should block until all the ASEC containers are finished being scanned.
23421     */
23422    public void scanAvailableAsecs() {
23423        updateExternalMediaStatusInner(true, false, false);
23424    }
23425
23426    /*
23427     * Collect information of applications on external media, map them against
23428     * existing containers and update information based on current mount status.
23429     * Please note that we always have to report status if reportStatus has been
23430     * set to true especially when unloading packages.
23431     */
23432    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23433            boolean externalStorage) {
23434        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23435        int[] uidArr = EmptyArray.INT;
23436
23437        final String[] list = PackageHelper.getSecureContainerList();
23438        if (ArrayUtils.isEmpty(list)) {
23439            Log.i(TAG, "No secure containers found");
23440        } else {
23441            // Process list of secure containers and categorize them
23442            // as active or stale based on their package internal state.
23443
23444            // reader
23445            synchronized (mPackages) {
23446                for (String cid : list) {
23447                    // Leave stages untouched for now; installer service owns them
23448                    if (PackageInstallerService.isStageName(cid)) continue;
23449
23450                    if (DEBUG_SD_INSTALL)
23451                        Log.i(TAG, "Processing container " + cid);
23452                    String pkgName = getAsecPackageName(cid);
23453                    if (pkgName == null) {
23454                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23455                        continue;
23456                    }
23457                    if (DEBUG_SD_INSTALL)
23458                        Log.i(TAG, "Looking for pkg : " + pkgName);
23459
23460                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23461                    if (ps == null) {
23462                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23463                        continue;
23464                    }
23465
23466                    /*
23467                     * Skip packages that are not external if we're unmounting
23468                     * external storage.
23469                     */
23470                    if (externalStorage && !isMounted && !isExternal(ps)) {
23471                        continue;
23472                    }
23473
23474                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23475                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23476                    // The package status is changed only if the code path
23477                    // matches between settings and the container id.
23478                    if (ps.codePathString != null
23479                            && ps.codePathString.startsWith(args.getCodePath())) {
23480                        if (DEBUG_SD_INSTALL) {
23481                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23482                                    + " at code path: " + ps.codePathString);
23483                        }
23484
23485                        // We do have a valid package installed on sdcard
23486                        processCids.put(args, ps.codePathString);
23487                        final int uid = ps.appId;
23488                        if (uid != -1) {
23489                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23490                        }
23491                    } else {
23492                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23493                                + ps.codePathString);
23494                    }
23495                }
23496            }
23497
23498            Arrays.sort(uidArr);
23499        }
23500
23501        // Process packages with valid entries.
23502        if (isMounted) {
23503            if (DEBUG_SD_INSTALL)
23504                Log.i(TAG, "Loading packages");
23505            loadMediaPackages(processCids, uidArr, externalStorage);
23506            startCleaningPackages();
23507            mInstallerService.onSecureContainersAvailable();
23508        } else {
23509            if (DEBUG_SD_INSTALL)
23510                Log.i(TAG, "Unloading packages");
23511            unloadMediaPackages(processCids, uidArr, reportStatus);
23512        }
23513    }
23514
23515    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23516            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23517        final int size = infos.size();
23518        final String[] packageNames = new String[size];
23519        final int[] packageUids = new int[size];
23520        for (int i = 0; i < size; i++) {
23521            final ApplicationInfo info = infos.get(i);
23522            packageNames[i] = info.packageName;
23523            packageUids[i] = info.uid;
23524        }
23525        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23526                finishedReceiver);
23527    }
23528
23529    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23530            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23531        sendResourcesChangedBroadcast(mediaStatus, replacing,
23532                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23533    }
23534
23535    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23536            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23537        int size = pkgList.length;
23538        if (size > 0) {
23539            // Send broadcasts here
23540            Bundle extras = new Bundle();
23541            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23542            if (uidArr != null) {
23543                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23544            }
23545            if (replacing) {
23546                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23547            }
23548            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23549                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23550            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23551        }
23552    }
23553
23554   /*
23555     * Look at potentially valid container ids from processCids If package
23556     * information doesn't match the one on record or package scanning fails,
23557     * the cid is added to list of removeCids. We currently don't delete stale
23558     * containers.
23559     */
23560    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23561            boolean externalStorage) {
23562        ArrayList<String> pkgList = new ArrayList<String>();
23563        Set<AsecInstallArgs> keys = processCids.keySet();
23564
23565        for (AsecInstallArgs args : keys) {
23566            String codePath = processCids.get(args);
23567            if (DEBUG_SD_INSTALL)
23568                Log.i(TAG, "Loading container : " + args.cid);
23569            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23570            try {
23571                // Make sure there are no container errors first.
23572                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23573                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23574                            + " when installing from sdcard");
23575                    continue;
23576                }
23577                // Check code path here.
23578                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23579                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23580                            + " does not match one in settings " + codePath);
23581                    continue;
23582                }
23583                // Parse package
23584                int parseFlags = mDefParseFlags;
23585                if (args.isExternalAsec()) {
23586                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23587                }
23588                if (args.isFwdLocked()) {
23589                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23590                }
23591
23592                synchronized (mInstallLock) {
23593                    PackageParser.Package pkg = null;
23594                    try {
23595                        // Sadly we don't know the package name yet to freeze it
23596                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23597                                SCAN_IGNORE_FROZEN, 0, null);
23598                    } catch (PackageManagerException e) {
23599                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23600                    }
23601                    // Scan the package
23602                    if (pkg != null) {
23603                        /*
23604                         * TODO why is the lock being held? doPostInstall is
23605                         * called in other places without the lock. This needs
23606                         * to be straightened out.
23607                         */
23608                        // writer
23609                        synchronized (mPackages) {
23610                            retCode = PackageManager.INSTALL_SUCCEEDED;
23611                            pkgList.add(pkg.packageName);
23612                            // Post process args
23613                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23614                                    pkg.applicationInfo.uid);
23615                        }
23616                    } else {
23617                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23618                    }
23619                }
23620
23621            } finally {
23622                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23623                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23624                }
23625            }
23626        }
23627        // writer
23628        synchronized (mPackages) {
23629            // If the platform SDK has changed since the last time we booted,
23630            // we need to re-grant app permission to catch any new ones that
23631            // appear. This is really a hack, and means that apps can in some
23632            // cases get permissions that the user didn't initially explicitly
23633            // allow... it would be nice to have some better way to handle
23634            // this situation.
23635            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23636                    : mSettings.getInternalVersion();
23637            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23638                    : StorageManager.UUID_PRIVATE_INTERNAL;
23639
23640            int updateFlags = UPDATE_PERMISSIONS_ALL;
23641            if (ver.sdkVersion != mSdkVersion) {
23642                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23643                        + mSdkVersion + "; regranting permissions for external");
23644                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23645            }
23646            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23647
23648            // Yay, everything is now upgraded
23649            ver.forceCurrent();
23650
23651            // can downgrade to reader
23652            // Persist settings
23653            mSettings.writeLPr();
23654        }
23655        // Send a broadcast to let everyone know we are done processing
23656        if (pkgList.size() > 0) {
23657            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23658        }
23659    }
23660
23661   /*
23662     * Utility method to unload a list of specified containers
23663     */
23664    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23665        // Just unmount all valid containers.
23666        for (AsecInstallArgs arg : cidArgs) {
23667            synchronized (mInstallLock) {
23668                arg.doPostDeleteLI(false);
23669           }
23670       }
23671   }
23672
23673    /*
23674     * Unload packages mounted on external media. This involves deleting package
23675     * data from internal structures, sending broadcasts about disabled packages,
23676     * gc'ing to free up references, unmounting all secure containers
23677     * corresponding to packages on external media, and posting a
23678     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23679     * that we always have to post this message if status has been requested no
23680     * matter what.
23681     */
23682    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23683            final boolean reportStatus) {
23684        if (DEBUG_SD_INSTALL)
23685            Log.i(TAG, "unloading media packages");
23686        ArrayList<String> pkgList = new ArrayList<String>();
23687        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23688        final Set<AsecInstallArgs> keys = processCids.keySet();
23689        for (AsecInstallArgs args : keys) {
23690            String pkgName = args.getPackageName();
23691            if (DEBUG_SD_INSTALL)
23692                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23693            // Delete package internally
23694            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23695            synchronized (mInstallLock) {
23696                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23697                final boolean res;
23698                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23699                        "unloadMediaPackages")) {
23700                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23701                            null);
23702                }
23703                if (res) {
23704                    pkgList.add(pkgName);
23705                } else {
23706                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23707                    failedList.add(args);
23708                }
23709            }
23710        }
23711
23712        // reader
23713        synchronized (mPackages) {
23714            // We didn't update the settings after removing each package;
23715            // write them now for all packages.
23716            mSettings.writeLPr();
23717        }
23718
23719        // We have to absolutely send UPDATED_MEDIA_STATUS only
23720        // after confirming that all the receivers processed the ordered
23721        // broadcast when packages get disabled, force a gc to clean things up.
23722        // and unload all the containers.
23723        if (pkgList.size() > 0) {
23724            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23725                    new IIntentReceiver.Stub() {
23726                public void performReceive(Intent intent, int resultCode, String data,
23727                        Bundle extras, boolean ordered, boolean sticky,
23728                        int sendingUser) throws RemoteException {
23729                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23730                            reportStatus ? 1 : 0, 1, keys);
23731                    mHandler.sendMessage(msg);
23732                }
23733            });
23734        } else {
23735            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23736                    keys);
23737            mHandler.sendMessage(msg);
23738        }
23739    }
23740
23741    private void loadPrivatePackages(final VolumeInfo vol) {
23742        mHandler.post(new Runnable() {
23743            @Override
23744            public void run() {
23745                loadPrivatePackagesInner(vol);
23746            }
23747        });
23748    }
23749
23750    private void loadPrivatePackagesInner(VolumeInfo vol) {
23751        final String volumeUuid = vol.fsUuid;
23752        if (TextUtils.isEmpty(volumeUuid)) {
23753            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23754            return;
23755        }
23756
23757        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23758        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23759        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23760
23761        final VersionInfo ver;
23762        final List<PackageSetting> packages;
23763        synchronized (mPackages) {
23764            ver = mSettings.findOrCreateVersion(volumeUuid);
23765            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23766        }
23767
23768        for (PackageSetting ps : packages) {
23769            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23770            synchronized (mInstallLock) {
23771                final PackageParser.Package pkg;
23772                try {
23773                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23774                    loaded.add(pkg.applicationInfo);
23775
23776                } catch (PackageManagerException e) {
23777                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23778                }
23779
23780                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23781                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23782                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23783                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23784                }
23785            }
23786        }
23787
23788        // Reconcile app data for all started/unlocked users
23789        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23790        final UserManager um = mContext.getSystemService(UserManager.class);
23791        UserManagerInternal umInternal = getUserManagerInternal();
23792        for (UserInfo user : um.getUsers()) {
23793            final int flags;
23794            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23795                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23796            } else if (umInternal.isUserRunning(user.id)) {
23797                flags = StorageManager.FLAG_STORAGE_DE;
23798            } else {
23799                continue;
23800            }
23801
23802            try {
23803                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23804                synchronized (mInstallLock) {
23805                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23806                }
23807            } catch (IllegalStateException e) {
23808                // Device was probably ejected, and we'll process that event momentarily
23809                Slog.w(TAG, "Failed to prepare storage: " + e);
23810            }
23811        }
23812
23813        synchronized (mPackages) {
23814            int updateFlags = UPDATE_PERMISSIONS_ALL;
23815            if (ver.sdkVersion != mSdkVersion) {
23816                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23817                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23818                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23819            }
23820            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23821
23822            // Yay, everything is now upgraded
23823            ver.forceCurrent();
23824
23825            mSettings.writeLPr();
23826        }
23827
23828        for (PackageFreezer freezer : freezers) {
23829            freezer.close();
23830        }
23831
23832        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23833        sendResourcesChangedBroadcast(true, false, loaded, null);
23834        mLoadedVolumes.add(vol.getId());
23835    }
23836
23837    private void unloadPrivatePackages(final VolumeInfo vol) {
23838        mHandler.post(new Runnable() {
23839            @Override
23840            public void run() {
23841                unloadPrivatePackagesInner(vol);
23842            }
23843        });
23844    }
23845
23846    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23847        final String volumeUuid = vol.fsUuid;
23848        if (TextUtils.isEmpty(volumeUuid)) {
23849            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23850            return;
23851        }
23852
23853        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23854        synchronized (mInstallLock) {
23855        synchronized (mPackages) {
23856            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23857            for (PackageSetting ps : packages) {
23858                if (ps.pkg == null) continue;
23859
23860                final ApplicationInfo info = ps.pkg.applicationInfo;
23861                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23862                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23863
23864                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23865                        "unloadPrivatePackagesInner")) {
23866                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23867                            false, null)) {
23868                        unloaded.add(info);
23869                    } else {
23870                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23871                    }
23872                }
23873
23874                // Try very hard to release any references to this package
23875                // so we don't risk the system server being killed due to
23876                // open FDs
23877                AttributeCache.instance().removePackage(ps.name);
23878            }
23879
23880            mSettings.writeLPr();
23881        }
23882        }
23883
23884        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23885        sendResourcesChangedBroadcast(false, false, unloaded, null);
23886        mLoadedVolumes.remove(vol.getId());
23887
23888        // Try very hard to release any references to this path so we don't risk
23889        // the system server being killed due to open FDs
23890        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23891
23892        for (int i = 0; i < 3; i++) {
23893            System.gc();
23894            System.runFinalization();
23895        }
23896    }
23897
23898    private void assertPackageKnown(String volumeUuid, String packageName)
23899            throws PackageManagerException {
23900        synchronized (mPackages) {
23901            // Normalize package name to handle renamed packages
23902            packageName = normalizePackageNameLPr(packageName);
23903
23904            final PackageSetting ps = mSettings.mPackages.get(packageName);
23905            if (ps == null) {
23906                throw new PackageManagerException("Package " + packageName + " is unknown");
23907            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23908                throw new PackageManagerException(
23909                        "Package " + packageName + " found on unknown volume " + volumeUuid
23910                                + "; expected volume " + ps.volumeUuid);
23911            }
23912        }
23913    }
23914
23915    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23916            throws PackageManagerException {
23917        synchronized (mPackages) {
23918            // Normalize package name to handle renamed packages
23919            packageName = normalizePackageNameLPr(packageName);
23920
23921            final PackageSetting ps = mSettings.mPackages.get(packageName);
23922            if (ps == null) {
23923                throw new PackageManagerException("Package " + packageName + " is unknown");
23924            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23925                throw new PackageManagerException(
23926                        "Package " + packageName + " found on unknown volume " + volumeUuid
23927                                + "; expected volume " + ps.volumeUuid);
23928            } else if (!ps.getInstalled(userId)) {
23929                throw new PackageManagerException(
23930                        "Package " + packageName + " not installed for user " + userId);
23931            }
23932        }
23933    }
23934
23935    private List<String> collectAbsoluteCodePaths() {
23936        synchronized (mPackages) {
23937            List<String> codePaths = new ArrayList<>();
23938            final int packageCount = mSettings.mPackages.size();
23939            for (int i = 0; i < packageCount; i++) {
23940                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23941                codePaths.add(ps.codePath.getAbsolutePath());
23942            }
23943            return codePaths;
23944        }
23945    }
23946
23947    /**
23948     * Examine all apps present on given mounted volume, and destroy apps that
23949     * aren't expected, either due to uninstallation or reinstallation on
23950     * another volume.
23951     */
23952    private void reconcileApps(String volumeUuid) {
23953        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23954        List<File> filesToDelete = null;
23955
23956        final File[] files = FileUtils.listFilesOrEmpty(
23957                Environment.getDataAppDirectory(volumeUuid));
23958        for (File file : files) {
23959            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23960                    && !PackageInstallerService.isStageName(file.getName());
23961            if (!isPackage) {
23962                // Ignore entries which are not packages
23963                continue;
23964            }
23965
23966            String absolutePath = file.getAbsolutePath();
23967
23968            boolean pathValid = false;
23969            final int absoluteCodePathCount = absoluteCodePaths.size();
23970            for (int i = 0; i < absoluteCodePathCount; i++) {
23971                String absoluteCodePath = absoluteCodePaths.get(i);
23972                if (absolutePath.startsWith(absoluteCodePath)) {
23973                    pathValid = true;
23974                    break;
23975                }
23976            }
23977
23978            if (!pathValid) {
23979                if (filesToDelete == null) {
23980                    filesToDelete = new ArrayList<>();
23981                }
23982                filesToDelete.add(file);
23983            }
23984        }
23985
23986        if (filesToDelete != null) {
23987            final int fileToDeleteCount = filesToDelete.size();
23988            for (int i = 0; i < fileToDeleteCount; i++) {
23989                File fileToDelete = filesToDelete.get(i);
23990                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23991                synchronized (mInstallLock) {
23992                    removeCodePathLI(fileToDelete);
23993                }
23994            }
23995        }
23996    }
23997
23998    /**
23999     * Reconcile all app data for the given user.
24000     * <p>
24001     * Verifies that directories exist and that ownership and labeling is
24002     * correct for all installed apps on all mounted volumes.
24003     */
24004    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
24005        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24006        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
24007            final String volumeUuid = vol.getFsUuid();
24008            synchronized (mInstallLock) {
24009                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
24010            }
24011        }
24012    }
24013
24014    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
24015            boolean migrateAppData) {
24016        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
24017    }
24018
24019    /**
24020     * Reconcile all app data on given mounted volume.
24021     * <p>
24022     * Destroys app data that isn't expected, either due to uninstallation or
24023     * reinstallation on another volume.
24024     * <p>
24025     * Verifies that directories exist and that ownership and labeling is
24026     * correct for all installed apps.
24027     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
24028     */
24029    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
24030            boolean migrateAppData, boolean onlyCoreApps) {
24031        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
24032                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
24033        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
24034
24035        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
24036        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
24037
24038        // First look for stale data that doesn't belong, and check if things
24039        // have changed since we did our last restorecon
24040        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24041            if (StorageManager.isFileEncryptedNativeOrEmulated()
24042                    && !StorageManager.isUserKeyUnlocked(userId)) {
24043                throw new RuntimeException(
24044                        "Yikes, someone asked us to reconcile CE storage while " + userId
24045                                + " was still locked; this would have caused massive data loss!");
24046            }
24047
24048            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
24049            for (File file : files) {
24050                final String packageName = file.getName();
24051                try {
24052                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24053                } catch (PackageManagerException e) {
24054                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24055                    try {
24056                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24057                                StorageManager.FLAG_STORAGE_CE, 0);
24058                    } catch (InstallerException e2) {
24059                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24060                    }
24061                }
24062            }
24063        }
24064        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
24065            final File[] files = FileUtils.listFilesOrEmpty(deDir);
24066            for (File file : files) {
24067                final String packageName = file.getName();
24068                try {
24069                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24070                } catch (PackageManagerException e) {
24071                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24072                    try {
24073                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24074                                StorageManager.FLAG_STORAGE_DE, 0);
24075                    } catch (InstallerException e2) {
24076                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24077                    }
24078                }
24079            }
24080        }
24081
24082        // Ensure that data directories are ready to roll for all packages
24083        // installed for this volume and user
24084        final List<PackageSetting> packages;
24085        synchronized (mPackages) {
24086            packages = mSettings.getVolumePackagesLPr(volumeUuid);
24087        }
24088        int preparedCount = 0;
24089        for (PackageSetting ps : packages) {
24090            final String packageName = ps.name;
24091            if (ps.pkg == null) {
24092                Slog.w(TAG, "Odd, missing scanned package " + packageName);
24093                // TODO: might be due to legacy ASEC apps; we should circle back
24094                // and reconcile again once they're scanned
24095                continue;
24096            }
24097            // Skip non-core apps if requested
24098            if (onlyCoreApps && !ps.pkg.coreApp) {
24099                result.add(packageName);
24100                continue;
24101            }
24102
24103            if (ps.getInstalled(userId)) {
24104                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
24105                preparedCount++;
24106            }
24107        }
24108
24109        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
24110        return result;
24111    }
24112
24113    /**
24114     * Prepare app data for the given app just after it was installed or
24115     * upgraded. This method carefully only touches users that it's installed
24116     * for, and it forces a restorecon to handle any seinfo changes.
24117     * <p>
24118     * Verifies that directories exist and that ownership and labeling is
24119     * correct for all installed apps. If there is an ownership mismatch, it
24120     * will try recovering system apps by wiping data; third-party app data is
24121     * left intact.
24122     * <p>
24123     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
24124     */
24125    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
24126        final PackageSetting ps;
24127        synchronized (mPackages) {
24128            ps = mSettings.mPackages.get(pkg.packageName);
24129            mSettings.writeKernelMappingLPr(ps);
24130        }
24131
24132        final UserManager um = mContext.getSystemService(UserManager.class);
24133        UserManagerInternal umInternal = getUserManagerInternal();
24134        for (UserInfo user : um.getUsers()) {
24135            final int flags;
24136            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
24137                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
24138            } else if (umInternal.isUserRunning(user.id)) {
24139                flags = StorageManager.FLAG_STORAGE_DE;
24140            } else {
24141                continue;
24142            }
24143
24144            if (ps.getInstalled(user.id)) {
24145                // TODO: when user data is locked, mark that we're still dirty
24146                prepareAppDataLIF(pkg, user.id, flags);
24147            }
24148        }
24149    }
24150
24151    /**
24152     * Prepare app data for the given app.
24153     * <p>
24154     * Verifies that directories exist and that ownership and labeling is
24155     * correct for all installed apps. If there is an ownership mismatch, this
24156     * will try recovering system apps by wiping data; third-party app data is
24157     * left intact.
24158     */
24159    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
24160        if (pkg == null) {
24161            Slog.wtf(TAG, "Package was null!", new Throwable());
24162            return;
24163        }
24164        prepareAppDataLeafLIF(pkg, userId, flags);
24165        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24166        for (int i = 0; i < childCount; i++) {
24167            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
24168        }
24169    }
24170
24171    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
24172            boolean maybeMigrateAppData) {
24173        prepareAppDataLIF(pkg, userId, flags);
24174
24175        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
24176            // We may have just shuffled around app data directories, so
24177            // prepare them one more time
24178            prepareAppDataLIF(pkg, userId, flags);
24179        }
24180    }
24181
24182    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24183        if (DEBUG_APP_DATA) {
24184            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
24185                    + Integer.toHexString(flags));
24186        }
24187
24188        final String volumeUuid = pkg.volumeUuid;
24189        final String packageName = pkg.packageName;
24190        final ApplicationInfo app = pkg.applicationInfo;
24191        final int appId = UserHandle.getAppId(app.uid);
24192
24193        Preconditions.checkNotNull(app.seInfo);
24194
24195        long ceDataInode = -1;
24196        try {
24197            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24198                    appId, app.seInfo, app.targetSdkVersion);
24199        } catch (InstallerException e) {
24200            if (app.isSystemApp()) {
24201                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
24202                        + ", but trying to recover: " + e);
24203                destroyAppDataLeafLIF(pkg, userId, flags);
24204                try {
24205                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24206                            appId, app.seInfo, app.targetSdkVersion);
24207                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
24208                } catch (InstallerException e2) {
24209                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
24210                }
24211            } else {
24212                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
24213            }
24214        }
24215        // Prepare the application profiles.
24216        mArtManagerService.prepareAppProfiles(pkg, userId);
24217
24218        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
24219            // TODO: mark this structure as dirty so we persist it!
24220            synchronized (mPackages) {
24221                final PackageSetting ps = mSettings.mPackages.get(packageName);
24222                if (ps != null) {
24223                    ps.setCeDataInode(ceDataInode, userId);
24224                }
24225            }
24226        }
24227
24228        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24229    }
24230
24231    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
24232        if (pkg == null) {
24233            Slog.wtf(TAG, "Package was null!", new Throwable());
24234            return;
24235        }
24236        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24237        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24238        for (int i = 0; i < childCount; i++) {
24239            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
24240        }
24241    }
24242
24243    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24244        final String volumeUuid = pkg.volumeUuid;
24245        final String packageName = pkg.packageName;
24246        final ApplicationInfo app = pkg.applicationInfo;
24247
24248        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24249            // Create a native library symlink only if we have native libraries
24250            // and if the native libraries are 32 bit libraries. We do not provide
24251            // this symlink for 64 bit libraries.
24252            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24253                final String nativeLibPath = app.nativeLibraryDir;
24254                try {
24255                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24256                            nativeLibPath, userId);
24257                } catch (InstallerException e) {
24258                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24259                }
24260            }
24261        }
24262    }
24263
24264    /**
24265     * For system apps on non-FBE devices, this method migrates any existing
24266     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24267     * requested by the app.
24268     */
24269    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24270        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24271                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24272            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24273                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24274            try {
24275                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24276                        storageTarget);
24277            } catch (InstallerException e) {
24278                logCriticalInfo(Log.WARN,
24279                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24280            }
24281            return true;
24282        } else {
24283            return false;
24284        }
24285    }
24286
24287    public PackageFreezer freezePackage(String packageName, String killReason) {
24288        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24289    }
24290
24291    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24292        return new PackageFreezer(packageName, userId, killReason);
24293    }
24294
24295    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24296            String killReason) {
24297        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24298    }
24299
24300    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24301            String killReason) {
24302        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24303            return new PackageFreezer();
24304        } else {
24305            return freezePackage(packageName, userId, killReason);
24306        }
24307    }
24308
24309    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24310            String killReason) {
24311        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24312    }
24313
24314    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24315            String killReason) {
24316        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24317            return new PackageFreezer();
24318        } else {
24319            return freezePackage(packageName, userId, killReason);
24320        }
24321    }
24322
24323    /**
24324     * Class that freezes and kills the given package upon creation, and
24325     * unfreezes it upon closing. This is typically used when doing surgery on
24326     * app code/data to prevent the app from running while you're working.
24327     */
24328    private class PackageFreezer implements AutoCloseable {
24329        private final String mPackageName;
24330        private final PackageFreezer[] mChildren;
24331
24332        private final boolean mWeFroze;
24333
24334        private final AtomicBoolean mClosed = new AtomicBoolean();
24335        private final CloseGuard mCloseGuard = CloseGuard.get();
24336
24337        /**
24338         * Create and return a stub freezer that doesn't actually do anything,
24339         * typically used when someone requested
24340         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24341         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24342         */
24343        public PackageFreezer() {
24344            mPackageName = null;
24345            mChildren = null;
24346            mWeFroze = false;
24347            mCloseGuard.open("close");
24348        }
24349
24350        public PackageFreezer(String packageName, int userId, String killReason) {
24351            synchronized (mPackages) {
24352                mPackageName = packageName;
24353                mWeFroze = mFrozenPackages.add(mPackageName);
24354
24355                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24356                if (ps != null) {
24357                    killApplication(ps.name, ps.appId, userId, killReason);
24358                }
24359
24360                final PackageParser.Package p = mPackages.get(packageName);
24361                if (p != null && p.childPackages != null) {
24362                    final int N = p.childPackages.size();
24363                    mChildren = new PackageFreezer[N];
24364                    for (int i = 0; i < N; i++) {
24365                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24366                                userId, killReason);
24367                    }
24368                } else {
24369                    mChildren = null;
24370                }
24371            }
24372            mCloseGuard.open("close");
24373        }
24374
24375        @Override
24376        protected void finalize() throws Throwable {
24377            try {
24378                if (mCloseGuard != null) {
24379                    mCloseGuard.warnIfOpen();
24380                }
24381
24382                close();
24383            } finally {
24384                super.finalize();
24385            }
24386        }
24387
24388        @Override
24389        public void close() {
24390            mCloseGuard.close();
24391            if (mClosed.compareAndSet(false, true)) {
24392                synchronized (mPackages) {
24393                    if (mWeFroze) {
24394                        mFrozenPackages.remove(mPackageName);
24395                    }
24396
24397                    if (mChildren != null) {
24398                        for (PackageFreezer freezer : mChildren) {
24399                            freezer.close();
24400                        }
24401                    }
24402                }
24403            }
24404        }
24405    }
24406
24407    /**
24408     * Verify that given package is currently frozen.
24409     */
24410    private void checkPackageFrozen(String packageName) {
24411        synchronized (mPackages) {
24412            if (!mFrozenPackages.contains(packageName)) {
24413                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24414            }
24415        }
24416    }
24417
24418    @Override
24419    public int movePackage(final String packageName, final String volumeUuid) {
24420        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24421
24422        final int callingUid = Binder.getCallingUid();
24423        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24424        final int moveId = mNextMoveId.getAndIncrement();
24425        mHandler.post(new Runnable() {
24426            @Override
24427            public void run() {
24428                try {
24429                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24430                } catch (PackageManagerException e) {
24431                    Slog.w(TAG, "Failed to move " + packageName, e);
24432                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24433                }
24434            }
24435        });
24436        return moveId;
24437    }
24438
24439    private void movePackageInternal(final String packageName, final String volumeUuid,
24440            final int moveId, final int callingUid, UserHandle user)
24441                    throws PackageManagerException {
24442        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24443        final PackageManager pm = mContext.getPackageManager();
24444
24445        final boolean currentAsec;
24446        final String currentVolumeUuid;
24447        final File codeFile;
24448        final String installerPackageName;
24449        final String packageAbiOverride;
24450        final int appId;
24451        final String seinfo;
24452        final String label;
24453        final int targetSdkVersion;
24454        final PackageFreezer freezer;
24455        final int[] installedUserIds;
24456
24457        // reader
24458        synchronized (mPackages) {
24459            final PackageParser.Package pkg = mPackages.get(packageName);
24460            final PackageSetting ps = mSettings.mPackages.get(packageName);
24461            if (pkg == null
24462                    || ps == null
24463                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24464                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24465            }
24466            if (pkg.applicationInfo.isSystemApp()) {
24467                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24468                        "Cannot move system application");
24469            }
24470
24471            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24472            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24473                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24474            if (isInternalStorage && !allow3rdPartyOnInternal) {
24475                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24476                        "3rd party apps are not allowed on internal storage");
24477            }
24478
24479            if (pkg.applicationInfo.isExternalAsec()) {
24480                currentAsec = true;
24481                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24482            } else if (pkg.applicationInfo.isForwardLocked()) {
24483                currentAsec = true;
24484                currentVolumeUuid = "forward_locked";
24485            } else {
24486                currentAsec = false;
24487                currentVolumeUuid = ps.volumeUuid;
24488
24489                final File probe = new File(pkg.codePath);
24490                final File probeOat = new File(probe, "oat");
24491                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24492                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24493                            "Move only supported for modern cluster style installs");
24494                }
24495            }
24496
24497            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24498                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24499                        "Package already moved to " + volumeUuid);
24500            }
24501            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24502                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24503                        "Device admin cannot be moved");
24504            }
24505
24506            if (mFrozenPackages.contains(packageName)) {
24507                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24508                        "Failed to move already frozen package");
24509            }
24510
24511            codeFile = new File(pkg.codePath);
24512            installerPackageName = ps.installerPackageName;
24513            packageAbiOverride = ps.cpuAbiOverrideString;
24514            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24515            seinfo = pkg.applicationInfo.seInfo;
24516            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24517            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24518            freezer = freezePackage(packageName, "movePackageInternal");
24519            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24520        }
24521
24522        final Bundle extras = new Bundle();
24523        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24524        extras.putString(Intent.EXTRA_TITLE, label);
24525        mMoveCallbacks.notifyCreated(moveId, extras);
24526
24527        int installFlags;
24528        final boolean moveCompleteApp;
24529        final File measurePath;
24530
24531        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24532            installFlags = INSTALL_INTERNAL;
24533            moveCompleteApp = !currentAsec;
24534            measurePath = Environment.getDataAppDirectory(volumeUuid);
24535        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24536            installFlags = INSTALL_EXTERNAL;
24537            moveCompleteApp = false;
24538            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24539        } else {
24540            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24541            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24542                    || !volume.isMountedWritable()) {
24543                freezer.close();
24544                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24545                        "Move location not mounted private volume");
24546            }
24547
24548            Preconditions.checkState(!currentAsec);
24549
24550            installFlags = INSTALL_INTERNAL;
24551            moveCompleteApp = true;
24552            measurePath = Environment.getDataAppDirectory(volumeUuid);
24553        }
24554
24555        // If we're moving app data around, we need all the users unlocked
24556        if (moveCompleteApp) {
24557            for (int userId : installedUserIds) {
24558                if (StorageManager.isFileEncryptedNativeOrEmulated()
24559                        && !StorageManager.isUserKeyUnlocked(userId)) {
24560                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24561                            "User " + userId + " must be unlocked");
24562                }
24563            }
24564        }
24565
24566        final PackageStats stats = new PackageStats(null, -1);
24567        synchronized (mInstaller) {
24568            for (int userId : installedUserIds) {
24569                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24570                    freezer.close();
24571                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24572                            "Failed to measure package size");
24573                }
24574            }
24575        }
24576
24577        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24578                + stats.dataSize);
24579
24580        final long startFreeBytes = measurePath.getUsableSpace();
24581        final long sizeBytes;
24582        if (moveCompleteApp) {
24583            sizeBytes = stats.codeSize + stats.dataSize;
24584        } else {
24585            sizeBytes = stats.codeSize;
24586        }
24587
24588        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24589            freezer.close();
24590            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24591                    "Not enough free space to move");
24592        }
24593
24594        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24595
24596        final CountDownLatch installedLatch = new CountDownLatch(1);
24597        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24598            @Override
24599            public void onUserActionRequired(Intent intent) throws RemoteException {
24600                throw new IllegalStateException();
24601            }
24602
24603            @Override
24604            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24605                    Bundle extras) throws RemoteException {
24606                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24607                        + PackageManager.installStatusToString(returnCode, msg));
24608
24609                installedLatch.countDown();
24610                freezer.close();
24611
24612                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24613                switch (status) {
24614                    case PackageInstaller.STATUS_SUCCESS:
24615                        mMoveCallbacks.notifyStatusChanged(moveId,
24616                                PackageManager.MOVE_SUCCEEDED);
24617                        break;
24618                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24619                        mMoveCallbacks.notifyStatusChanged(moveId,
24620                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24621                        break;
24622                    default:
24623                        mMoveCallbacks.notifyStatusChanged(moveId,
24624                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24625                        break;
24626                }
24627            }
24628        };
24629
24630        final MoveInfo move;
24631        if (moveCompleteApp) {
24632            // Kick off a thread to report progress estimates
24633            new Thread() {
24634                @Override
24635                public void run() {
24636                    while (true) {
24637                        try {
24638                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24639                                break;
24640                            }
24641                        } catch (InterruptedException ignored) {
24642                        }
24643
24644                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24645                        final int progress = 10 + (int) MathUtils.constrain(
24646                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24647                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24648                    }
24649                }
24650            }.start();
24651
24652            final String dataAppName = codeFile.getName();
24653            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24654                    dataAppName, appId, seinfo, targetSdkVersion);
24655        } else {
24656            move = null;
24657        }
24658
24659        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24660
24661        final Message msg = mHandler.obtainMessage(INIT_COPY);
24662        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24663        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24664                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24665                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24666                PackageManager.INSTALL_REASON_UNKNOWN);
24667        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24668        msg.obj = params;
24669
24670        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24671                System.identityHashCode(msg.obj));
24672        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24673                System.identityHashCode(msg.obj));
24674
24675        mHandler.sendMessage(msg);
24676    }
24677
24678    @Override
24679    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24680        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24681
24682        final int realMoveId = mNextMoveId.getAndIncrement();
24683        final Bundle extras = new Bundle();
24684        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24685        mMoveCallbacks.notifyCreated(realMoveId, extras);
24686
24687        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24688            @Override
24689            public void onCreated(int moveId, Bundle extras) {
24690                // Ignored
24691            }
24692
24693            @Override
24694            public void onStatusChanged(int moveId, int status, long estMillis) {
24695                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24696            }
24697        };
24698
24699        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24700        storage.setPrimaryStorageUuid(volumeUuid, callback);
24701        return realMoveId;
24702    }
24703
24704    @Override
24705    public int getMoveStatus(int moveId) {
24706        mContext.enforceCallingOrSelfPermission(
24707                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24708        return mMoveCallbacks.mLastStatus.get(moveId);
24709    }
24710
24711    @Override
24712    public void registerMoveCallback(IPackageMoveObserver callback) {
24713        mContext.enforceCallingOrSelfPermission(
24714                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24715        mMoveCallbacks.register(callback);
24716    }
24717
24718    @Override
24719    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24720        mContext.enforceCallingOrSelfPermission(
24721                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24722        mMoveCallbacks.unregister(callback);
24723    }
24724
24725    @Override
24726    public boolean setInstallLocation(int loc) {
24727        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24728                null);
24729        if (getInstallLocation() == loc) {
24730            return true;
24731        }
24732        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24733                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24734            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24735                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24736            return true;
24737        }
24738        return false;
24739   }
24740
24741    @Override
24742    public int getInstallLocation() {
24743        // allow instant app access
24744        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24745                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24746                PackageHelper.APP_INSTALL_AUTO);
24747    }
24748
24749    /** Called by UserManagerService */
24750    void cleanUpUser(UserManagerService userManager, int userHandle) {
24751        synchronized (mPackages) {
24752            mDirtyUsers.remove(userHandle);
24753            mUserNeedsBadging.delete(userHandle);
24754            mSettings.removeUserLPw(userHandle);
24755            mPendingBroadcasts.remove(userHandle);
24756            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24757            removeUnusedPackagesLPw(userManager, userHandle);
24758        }
24759    }
24760
24761    /**
24762     * We're removing userHandle and would like to remove any downloaded packages
24763     * that are no longer in use by any other user.
24764     * @param userHandle the user being removed
24765     */
24766    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24767        final boolean DEBUG_CLEAN_APKS = false;
24768        int [] users = userManager.getUserIds();
24769        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24770        while (psit.hasNext()) {
24771            PackageSetting ps = psit.next();
24772            if (ps.pkg == null) {
24773                continue;
24774            }
24775            final String packageName = ps.pkg.packageName;
24776            // Skip over if system app
24777            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24778                continue;
24779            }
24780            if (DEBUG_CLEAN_APKS) {
24781                Slog.i(TAG, "Checking package " + packageName);
24782            }
24783            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24784            if (keep) {
24785                if (DEBUG_CLEAN_APKS) {
24786                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24787                }
24788            } else {
24789                for (int i = 0; i < users.length; i++) {
24790                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24791                        keep = true;
24792                        if (DEBUG_CLEAN_APKS) {
24793                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24794                                    + users[i]);
24795                        }
24796                        break;
24797                    }
24798                }
24799            }
24800            if (!keep) {
24801                if (DEBUG_CLEAN_APKS) {
24802                    Slog.i(TAG, "  Removing package " + packageName);
24803                }
24804                mHandler.post(new Runnable() {
24805                    public void run() {
24806                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24807                                userHandle, 0);
24808                    } //end run
24809                });
24810            }
24811        }
24812    }
24813
24814    /** Called by UserManagerService */
24815    void createNewUser(int userId, String[] disallowedPackages) {
24816        synchronized (mInstallLock) {
24817            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24818        }
24819        synchronized (mPackages) {
24820            scheduleWritePackageRestrictionsLocked(userId);
24821            scheduleWritePackageListLocked(userId);
24822            applyFactoryDefaultBrowserLPw(userId);
24823            primeDomainVerificationsLPw(userId);
24824        }
24825    }
24826
24827    void onNewUserCreated(final int userId) {
24828        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24829        // If permission review for legacy apps is required, we represent
24830        // dagerous permissions for such apps as always granted runtime
24831        // permissions to keep per user flag state whether review is needed.
24832        // Hence, if a new user is added we have to propagate dangerous
24833        // permission grants for these legacy apps.
24834        if (mPermissionReviewRequired) {
24835            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24836                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24837        }
24838    }
24839
24840    @Override
24841    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24842        mContext.enforceCallingOrSelfPermission(
24843                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24844                "Only package verification agents can read the verifier device identity");
24845
24846        synchronized (mPackages) {
24847            return mSettings.getVerifierDeviceIdentityLPw();
24848        }
24849    }
24850
24851    @Override
24852    public void setPermissionEnforced(String permission, boolean enforced) {
24853        // TODO: Now that we no longer change GID for storage, this should to away.
24854        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24855                "setPermissionEnforced");
24856        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24857            synchronized (mPackages) {
24858                if (mSettings.mReadExternalStorageEnforced == null
24859                        || mSettings.mReadExternalStorageEnforced != enforced) {
24860                    mSettings.mReadExternalStorageEnforced = enforced;
24861                    mSettings.writeLPr();
24862                }
24863            }
24864            // kill any non-foreground processes so we restart them and
24865            // grant/revoke the GID.
24866            final IActivityManager am = ActivityManager.getService();
24867            if (am != null) {
24868                final long token = Binder.clearCallingIdentity();
24869                try {
24870                    am.killProcessesBelowForeground("setPermissionEnforcement");
24871                } catch (RemoteException e) {
24872                } finally {
24873                    Binder.restoreCallingIdentity(token);
24874                }
24875            }
24876        } else {
24877            throw new IllegalArgumentException("No selective enforcement for " + permission);
24878        }
24879    }
24880
24881    @Override
24882    @Deprecated
24883    public boolean isPermissionEnforced(String permission) {
24884        // allow instant applications
24885        return true;
24886    }
24887
24888    @Override
24889    public boolean isStorageLow() {
24890        // allow instant applications
24891        final long token = Binder.clearCallingIdentity();
24892        try {
24893            final DeviceStorageMonitorInternal
24894                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24895            if (dsm != null) {
24896                return dsm.isMemoryLow();
24897            } else {
24898                return false;
24899            }
24900        } finally {
24901            Binder.restoreCallingIdentity(token);
24902        }
24903    }
24904
24905    @Override
24906    public IPackageInstaller getPackageInstaller() {
24907        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24908            return null;
24909        }
24910        return mInstallerService;
24911    }
24912
24913    @Override
24914    public IArtManager getArtManager() {
24915        return mArtManagerService;
24916    }
24917
24918    private boolean userNeedsBadging(int userId) {
24919        int index = mUserNeedsBadging.indexOfKey(userId);
24920        if (index < 0) {
24921            final UserInfo userInfo;
24922            final long token = Binder.clearCallingIdentity();
24923            try {
24924                userInfo = sUserManager.getUserInfo(userId);
24925            } finally {
24926                Binder.restoreCallingIdentity(token);
24927            }
24928            final boolean b;
24929            if (userInfo != null && userInfo.isManagedProfile()) {
24930                b = true;
24931            } else {
24932                b = false;
24933            }
24934            mUserNeedsBadging.put(userId, b);
24935            return b;
24936        }
24937        return mUserNeedsBadging.valueAt(index);
24938    }
24939
24940    @Override
24941    public KeySet getKeySetByAlias(String packageName, String alias) {
24942        if (packageName == null || alias == null) {
24943            return null;
24944        }
24945        synchronized(mPackages) {
24946            final PackageParser.Package pkg = mPackages.get(packageName);
24947            if (pkg == null) {
24948                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24949                throw new IllegalArgumentException("Unknown package: " + packageName);
24950            }
24951            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24952            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24953                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24954                throw new IllegalArgumentException("Unknown package: " + packageName);
24955            }
24956            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24957            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24958        }
24959    }
24960
24961    @Override
24962    public KeySet getSigningKeySet(String packageName) {
24963        if (packageName == null) {
24964            return null;
24965        }
24966        synchronized(mPackages) {
24967            final int callingUid = Binder.getCallingUid();
24968            final int callingUserId = UserHandle.getUserId(callingUid);
24969            final PackageParser.Package pkg = mPackages.get(packageName);
24970            if (pkg == null) {
24971                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24972                throw new IllegalArgumentException("Unknown package: " + packageName);
24973            }
24974            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24975            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24976                // filter and pretend the package doesn't exist
24977                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24978                        + ", uid:" + callingUid);
24979                throw new IllegalArgumentException("Unknown package: " + packageName);
24980            }
24981            if (pkg.applicationInfo.uid != callingUid
24982                    && Process.SYSTEM_UID != callingUid) {
24983                throw new SecurityException("May not access signing KeySet of other apps.");
24984            }
24985            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24986            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24987        }
24988    }
24989
24990    @Override
24991    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24992        final int callingUid = Binder.getCallingUid();
24993        if (getInstantAppPackageName(callingUid) != null) {
24994            return false;
24995        }
24996        if (packageName == null || ks == null) {
24997            return false;
24998        }
24999        synchronized(mPackages) {
25000            final PackageParser.Package pkg = mPackages.get(packageName);
25001            if (pkg == null
25002                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
25003                            UserHandle.getUserId(callingUid))) {
25004                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
25005                throw new IllegalArgumentException("Unknown package: " + packageName);
25006            }
25007            IBinder ksh = ks.getToken();
25008            if (ksh instanceof KeySetHandle) {
25009                KeySetManagerService ksms = mSettings.mKeySetManagerService;
25010                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
25011            }
25012            return false;
25013        }
25014    }
25015
25016    @Override
25017    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
25018        final int callingUid = Binder.getCallingUid();
25019        if (getInstantAppPackageName(callingUid) != null) {
25020            return false;
25021        }
25022        if (packageName == null || ks == null) {
25023            return false;
25024        }
25025        synchronized(mPackages) {
25026            final PackageParser.Package pkg = mPackages.get(packageName);
25027            if (pkg == null
25028                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
25029                            UserHandle.getUserId(callingUid))) {
25030                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
25031                throw new IllegalArgumentException("Unknown package: " + packageName);
25032            }
25033            IBinder ksh = ks.getToken();
25034            if (ksh instanceof KeySetHandle) {
25035                KeySetManagerService ksms = mSettings.mKeySetManagerService;
25036                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
25037            }
25038            return false;
25039        }
25040    }
25041
25042    private void deletePackageIfUnusedLPr(final String packageName) {
25043        PackageSetting ps = mSettings.mPackages.get(packageName);
25044        if (ps == null) {
25045            return;
25046        }
25047        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
25048            // TODO Implement atomic delete if package is unused
25049            // It is currently possible that the package will be deleted even if it is installed
25050            // after this method returns.
25051            mHandler.post(new Runnable() {
25052                public void run() {
25053                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
25054                            0, PackageManager.DELETE_ALL_USERS);
25055                }
25056            });
25057        }
25058    }
25059
25060    /**
25061     * Check and throw if the given before/after packages would be considered a
25062     * downgrade.
25063     */
25064    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
25065            throws PackageManagerException {
25066        if (after.versionCode < before.mVersionCode) {
25067            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25068                    "Update version code " + after.versionCode + " is older than current "
25069                    + before.mVersionCode);
25070        } else if (after.versionCode == before.mVersionCode) {
25071            if (after.baseRevisionCode < before.baseRevisionCode) {
25072                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25073                        "Update base revision code " + after.baseRevisionCode
25074                        + " is older than current " + before.baseRevisionCode);
25075            }
25076
25077            if (!ArrayUtils.isEmpty(after.splitNames)) {
25078                for (int i = 0; i < after.splitNames.length; i++) {
25079                    final String splitName = after.splitNames[i];
25080                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
25081                    if (j != -1) {
25082                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
25083                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25084                                    "Update split " + splitName + " revision code "
25085                                    + after.splitRevisionCodes[i] + " is older than current "
25086                                    + before.splitRevisionCodes[j]);
25087                        }
25088                    }
25089                }
25090            }
25091        }
25092    }
25093
25094    private static class MoveCallbacks extends Handler {
25095        private static final int MSG_CREATED = 1;
25096        private static final int MSG_STATUS_CHANGED = 2;
25097
25098        private final RemoteCallbackList<IPackageMoveObserver>
25099                mCallbacks = new RemoteCallbackList<>();
25100
25101        private final SparseIntArray mLastStatus = new SparseIntArray();
25102
25103        public MoveCallbacks(Looper looper) {
25104            super(looper);
25105        }
25106
25107        public void register(IPackageMoveObserver callback) {
25108            mCallbacks.register(callback);
25109        }
25110
25111        public void unregister(IPackageMoveObserver callback) {
25112            mCallbacks.unregister(callback);
25113        }
25114
25115        @Override
25116        public void handleMessage(Message msg) {
25117            final SomeArgs args = (SomeArgs) msg.obj;
25118            final int n = mCallbacks.beginBroadcast();
25119            for (int i = 0; i < n; i++) {
25120                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
25121                try {
25122                    invokeCallback(callback, msg.what, args);
25123                } catch (RemoteException ignored) {
25124                }
25125            }
25126            mCallbacks.finishBroadcast();
25127            args.recycle();
25128        }
25129
25130        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
25131                throws RemoteException {
25132            switch (what) {
25133                case MSG_CREATED: {
25134                    callback.onCreated(args.argi1, (Bundle) args.arg2);
25135                    break;
25136                }
25137                case MSG_STATUS_CHANGED: {
25138                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
25139                    break;
25140                }
25141            }
25142        }
25143
25144        private void notifyCreated(int moveId, Bundle extras) {
25145            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
25146
25147            final SomeArgs args = SomeArgs.obtain();
25148            args.argi1 = moveId;
25149            args.arg2 = extras;
25150            obtainMessage(MSG_CREATED, args).sendToTarget();
25151        }
25152
25153        private void notifyStatusChanged(int moveId, int status) {
25154            notifyStatusChanged(moveId, status, -1);
25155        }
25156
25157        private void notifyStatusChanged(int moveId, int status, long estMillis) {
25158            Slog.v(TAG, "Move " + moveId + " status " + status);
25159
25160            final SomeArgs args = SomeArgs.obtain();
25161            args.argi1 = moveId;
25162            args.argi2 = status;
25163            args.arg3 = estMillis;
25164            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
25165
25166            synchronized (mLastStatus) {
25167                mLastStatus.put(moveId, status);
25168            }
25169        }
25170    }
25171
25172    private final static class OnPermissionChangeListeners extends Handler {
25173        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
25174
25175        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
25176                new RemoteCallbackList<>();
25177
25178        public OnPermissionChangeListeners(Looper looper) {
25179            super(looper);
25180        }
25181
25182        @Override
25183        public void handleMessage(Message msg) {
25184            switch (msg.what) {
25185                case MSG_ON_PERMISSIONS_CHANGED: {
25186                    final int uid = msg.arg1;
25187                    handleOnPermissionsChanged(uid);
25188                } break;
25189            }
25190        }
25191
25192        public void addListenerLocked(IOnPermissionsChangeListener listener) {
25193            mPermissionListeners.register(listener);
25194
25195        }
25196
25197        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
25198            mPermissionListeners.unregister(listener);
25199        }
25200
25201        public void onPermissionsChanged(int uid) {
25202            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
25203                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
25204            }
25205        }
25206
25207        private void handleOnPermissionsChanged(int uid) {
25208            final int count = mPermissionListeners.beginBroadcast();
25209            try {
25210                for (int i = 0; i < count; i++) {
25211                    IOnPermissionsChangeListener callback = mPermissionListeners
25212                            .getBroadcastItem(i);
25213                    try {
25214                        callback.onPermissionsChanged(uid);
25215                    } catch (RemoteException e) {
25216                        Log.e(TAG, "Permission listener is dead", e);
25217                    }
25218                }
25219            } finally {
25220                mPermissionListeners.finishBroadcast();
25221            }
25222        }
25223    }
25224
25225    private class PackageManagerNative extends IPackageManagerNative.Stub {
25226        @Override
25227        public String[] getNamesForUids(int[] uids) throws RemoteException {
25228            final String[] results = PackageManagerService.this.getNamesForUids(uids);
25229            // massage results so they can be parsed by the native binder
25230            for (int i = results.length - 1; i >= 0; --i) {
25231                if (results[i] == null) {
25232                    results[i] = "";
25233                }
25234            }
25235            return results;
25236        }
25237
25238        // NB: this differentiates between preloads and sideloads
25239        @Override
25240        public String getInstallerForPackage(String packageName) throws RemoteException {
25241            final String installerName = getInstallerPackageName(packageName);
25242            if (!TextUtils.isEmpty(installerName)) {
25243                return installerName;
25244            }
25245            // differentiate between preload and sideload
25246            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25247            ApplicationInfo appInfo = getApplicationInfo(packageName,
25248                                    /*flags*/ 0,
25249                                    /*userId*/ callingUser);
25250            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
25251                return "preload";
25252            }
25253            return "";
25254        }
25255
25256        @Override
25257        public int getVersionCodeForPackage(String packageName) throws RemoteException {
25258            try {
25259                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25260                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
25261                if (pInfo != null) {
25262                    return pInfo.versionCode;
25263                }
25264            } catch (Exception e) {
25265            }
25266            return 0;
25267        }
25268    }
25269
25270    private class PackageManagerInternalImpl extends PackageManagerInternal {
25271        @Override
25272        public void setLocationPackagesProvider(PackagesProvider provider) {
25273            synchronized (mPackages) {
25274                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
25275            }
25276        }
25277
25278        @Override
25279        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25280            synchronized (mPackages) {
25281                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
25282            }
25283        }
25284
25285        @Override
25286        public void setSmsAppPackagesProvider(PackagesProvider provider) {
25287            synchronized (mPackages) {
25288                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
25289            }
25290        }
25291
25292        @Override
25293        public void setDialerAppPackagesProvider(PackagesProvider provider) {
25294            synchronized (mPackages) {
25295                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
25296            }
25297        }
25298
25299        @Override
25300        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25301            synchronized (mPackages) {
25302                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
25303            }
25304        }
25305
25306        @Override
25307        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25308            synchronized (mPackages) {
25309                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25310            }
25311        }
25312
25313        @Override
25314        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25315            synchronized (mPackages) {
25316                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25317                        packageName, userId);
25318            }
25319        }
25320
25321        @Override
25322        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25323            synchronized (mPackages) {
25324                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25325                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25326                        packageName, userId);
25327            }
25328        }
25329
25330        @Override
25331        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25332            synchronized (mPackages) {
25333                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25334                        packageName, userId);
25335            }
25336        }
25337
25338        @Override
25339        public void setKeepUninstalledPackages(final List<String> packageList) {
25340            Preconditions.checkNotNull(packageList);
25341            List<String> removedFromList = null;
25342            synchronized (mPackages) {
25343                if (mKeepUninstalledPackages != null) {
25344                    final int packagesCount = mKeepUninstalledPackages.size();
25345                    for (int i = 0; i < packagesCount; i++) {
25346                        String oldPackage = mKeepUninstalledPackages.get(i);
25347                        if (packageList != null && packageList.contains(oldPackage)) {
25348                            continue;
25349                        }
25350                        if (removedFromList == null) {
25351                            removedFromList = new ArrayList<>();
25352                        }
25353                        removedFromList.add(oldPackage);
25354                    }
25355                }
25356                mKeepUninstalledPackages = new ArrayList<>(packageList);
25357                if (removedFromList != null) {
25358                    final int removedCount = removedFromList.size();
25359                    for (int i = 0; i < removedCount; i++) {
25360                        deletePackageIfUnusedLPr(removedFromList.get(i));
25361                    }
25362                }
25363            }
25364        }
25365
25366        @Override
25367        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25368            synchronized (mPackages) {
25369                // If we do not support permission review, done.
25370                if (!mPermissionReviewRequired) {
25371                    return false;
25372                }
25373
25374                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25375                if (packageSetting == null) {
25376                    return false;
25377                }
25378
25379                // Permission review applies only to apps not supporting the new permission model.
25380                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25381                    return false;
25382                }
25383
25384                // Legacy apps have the permission and get user consent on launch.
25385                PermissionsState permissionsState = packageSetting.getPermissionsState();
25386                return permissionsState.isPermissionReviewRequired(userId);
25387            }
25388        }
25389
25390        @Override
25391        public PackageInfo getPackageInfo(
25392                String packageName, int flags, int filterCallingUid, int userId) {
25393            return PackageManagerService.this
25394                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25395                            flags, filterCallingUid, userId);
25396        }
25397
25398        @Override
25399        public ApplicationInfo getApplicationInfo(
25400                String packageName, int flags, int filterCallingUid, int userId) {
25401            return PackageManagerService.this
25402                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25403        }
25404
25405        @Override
25406        public ActivityInfo getActivityInfo(
25407                ComponentName component, int flags, int filterCallingUid, int userId) {
25408            return PackageManagerService.this
25409                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25410        }
25411
25412        @Override
25413        public List<ResolveInfo> queryIntentActivities(
25414                Intent intent, int flags, int filterCallingUid, int userId) {
25415            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25416            return PackageManagerService.this
25417                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25418                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25419        }
25420
25421        @Override
25422        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25423                int userId) {
25424            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25425        }
25426
25427        @Override
25428        public void setDeviceAndProfileOwnerPackages(
25429                int deviceOwnerUserId, String deviceOwnerPackage,
25430                SparseArray<String> profileOwnerPackages) {
25431            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25432                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25433        }
25434
25435        @Override
25436        public boolean isPackageDataProtected(int userId, String packageName) {
25437            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25438        }
25439
25440        @Override
25441        public boolean isPackageEphemeral(int userId, String packageName) {
25442            synchronized (mPackages) {
25443                final PackageSetting ps = mSettings.mPackages.get(packageName);
25444                return ps != null ? ps.getInstantApp(userId) : false;
25445            }
25446        }
25447
25448        @Override
25449        public boolean wasPackageEverLaunched(String packageName, int userId) {
25450            synchronized (mPackages) {
25451                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25452            }
25453        }
25454
25455        @Override
25456        public void grantRuntimePermission(String packageName, String name, int userId,
25457                boolean overridePolicy) {
25458            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25459                    overridePolicy);
25460        }
25461
25462        @Override
25463        public void revokeRuntimePermission(String packageName, String name, int userId,
25464                boolean overridePolicy) {
25465            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25466                    overridePolicy);
25467        }
25468
25469        @Override
25470        public String getNameForUid(int uid) {
25471            return PackageManagerService.this.getNameForUid(uid);
25472        }
25473
25474        @Override
25475        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25476                Intent origIntent, String resolvedType, String callingPackage,
25477                Bundle verificationBundle, int userId) {
25478            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25479                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25480                    userId);
25481        }
25482
25483        @Override
25484        public void grantEphemeralAccess(int userId, Intent intent,
25485                int targetAppId, int ephemeralAppId) {
25486            synchronized (mPackages) {
25487                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25488                        targetAppId, ephemeralAppId);
25489            }
25490        }
25491
25492        @Override
25493        public boolean isInstantAppInstallerComponent(ComponentName component) {
25494            synchronized (mPackages) {
25495                return mInstantAppInstallerActivity != null
25496                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25497            }
25498        }
25499
25500        @Override
25501        public void pruneInstantApps() {
25502            mInstantAppRegistry.pruneInstantApps();
25503        }
25504
25505        @Override
25506        public String getSetupWizardPackageName() {
25507            return mSetupWizardPackage;
25508        }
25509
25510        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25511            if (policy != null) {
25512                mExternalSourcesPolicy = policy;
25513            }
25514        }
25515
25516        @Override
25517        public boolean isPackagePersistent(String packageName) {
25518            synchronized (mPackages) {
25519                PackageParser.Package pkg = mPackages.get(packageName);
25520                return pkg != null
25521                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25522                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25523                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25524                        : false;
25525            }
25526        }
25527
25528        @Override
25529        public List<PackageInfo> getOverlayPackages(int userId) {
25530            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25531            synchronized (mPackages) {
25532                for (PackageParser.Package p : mPackages.values()) {
25533                    if (p.mOverlayTarget != null) {
25534                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25535                        if (pkg != null) {
25536                            overlayPackages.add(pkg);
25537                        }
25538                    }
25539                }
25540            }
25541            return overlayPackages;
25542        }
25543
25544        @Override
25545        public List<String> getTargetPackageNames(int userId) {
25546            List<String> targetPackages = new ArrayList<>();
25547            synchronized (mPackages) {
25548                for (PackageParser.Package p : mPackages.values()) {
25549                    if (p.mOverlayTarget == null) {
25550                        targetPackages.add(p.packageName);
25551                    }
25552                }
25553            }
25554            return targetPackages;
25555        }
25556
25557        @Override
25558        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25559                @Nullable List<String> overlayPackageNames) {
25560            synchronized (mPackages) {
25561                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25562                    Slog.e(TAG, "failed to find package " + targetPackageName);
25563                    return false;
25564                }
25565                ArrayList<String> overlayPaths = null;
25566                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25567                    final int N = overlayPackageNames.size();
25568                    overlayPaths = new ArrayList<>(N);
25569                    for (int i = 0; i < N; i++) {
25570                        final String packageName = overlayPackageNames.get(i);
25571                        final PackageParser.Package pkg = mPackages.get(packageName);
25572                        if (pkg == null) {
25573                            Slog.e(TAG, "failed to find package " + packageName);
25574                            return false;
25575                        }
25576                        overlayPaths.add(pkg.baseCodePath);
25577                    }
25578                }
25579
25580                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25581                ps.setOverlayPaths(overlayPaths, userId);
25582                return true;
25583            }
25584        }
25585
25586        @Override
25587        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25588                int flags, int userId) {
25589            return resolveIntentInternal(
25590                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25591        }
25592
25593        @Override
25594        public ResolveInfo resolveService(Intent intent, String resolvedType,
25595                int flags, int userId, int callingUid) {
25596            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25597        }
25598
25599        @Override
25600        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25601            synchronized (mPackages) {
25602                mIsolatedOwners.put(isolatedUid, ownerUid);
25603            }
25604        }
25605
25606        @Override
25607        public void removeIsolatedUid(int isolatedUid) {
25608            synchronized (mPackages) {
25609                mIsolatedOwners.delete(isolatedUid);
25610            }
25611        }
25612
25613        @Override
25614        public int getUidTargetSdkVersion(int uid) {
25615            synchronized (mPackages) {
25616                return getUidTargetSdkVersionLockedLPr(uid);
25617            }
25618        }
25619
25620        @Override
25621        public boolean canAccessInstantApps(int callingUid, int userId) {
25622            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25623        }
25624
25625        @Override
25626        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
25627            synchronized (mPackages) {
25628                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
25629            }
25630        }
25631
25632        @Override
25633        public void notifyPackageUse(String packageName, int reason) {
25634            synchronized (mPackages) {
25635                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
25636            }
25637        }
25638    }
25639
25640    @Override
25641    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25642        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25643        synchronized (mPackages) {
25644            final long identity = Binder.clearCallingIdentity();
25645            try {
25646                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25647                        packageNames, userId);
25648            } finally {
25649                Binder.restoreCallingIdentity(identity);
25650            }
25651        }
25652    }
25653
25654    @Override
25655    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25656        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25657        synchronized (mPackages) {
25658            final long identity = Binder.clearCallingIdentity();
25659            try {
25660                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25661                        packageNames, userId);
25662            } finally {
25663                Binder.restoreCallingIdentity(identity);
25664            }
25665        }
25666    }
25667
25668    private static void enforceSystemOrPhoneCaller(String tag) {
25669        int callingUid = Binder.getCallingUid();
25670        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25671            throw new SecurityException(
25672                    "Cannot call " + tag + " from UID " + callingUid);
25673        }
25674    }
25675
25676    boolean isHistoricalPackageUsageAvailable() {
25677        return mPackageUsage.isHistoricalPackageUsageAvailable();
25678    }
25679
25680    /**
25681     * Return a <b>copy</b> of the collection of packages known to the package manager.
25682     * @return A copy of the values of mPackages.
25683     */
25684    Collection<PackageParser.Package> getPackages() {
25685        synchronized (mPackages) {
25686            return new ArrayList<>(mPackages.values());
25687        }
25688    }
25689
25690    /**
25691     * Logs process start information (including base APK hash) to the security log.
25692     * @hide
25693     */
25694    @Override
25695    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25696            String apkFile, int pid) {
25697        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25698            return;
25699        }
25700        if (!SecurityLog.isLoggingEnabled()) {
25701            return;
25702        }
25703        Bundle data = new Bundle();
25704        data.putLong("startTimestamp", System.currentTimeMillis());
25705        data.putString("processName", processName);
25706        data.putInt("uid", uid);
25707        data.putString("seinfo", seinfo);
25708        data.putString("apkFile", apkFile);
25709        data.putInt("pid", pid);
25710        Message msg = mProcessLoggingHandler.obtainMessage(
25711                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25712        msg.setData(data);
25713        mProcessLoggingHandler.sendMessage(msg);
25714    }
25715
25716    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25717        return mCompilerStats.getPackageStats(pkgName);
25718    }
25719
25720    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25721        return getOrCreateCompilerPackageStats(pkg.packageName);
25722    }
25723
25724    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25725        return mCompilerStats.getOrCreatePackageStats(pkgName);
25726    }
25727
25728    public void deleteCompilerPackageStats(String pkgName) {
25729        mCompilerStats.deletePackageStats(pkgName);
25730    }
25731
25732    @Override
25733    public int getInstallReason(String packageName, int userId) {
25734        final int callingUid = Binder.getCallingUid();
25735        enforceCrossUserPermission(callingUid, userId,
25736                true /* requireFullPermission */, false /* checkShell */,
25737                "get install reason");
25738        synchronized (mPackages) {
25739            final PackageSetting ps = mSettings.mPackages.get(packageName);
25740            if (filterAppAccessLPr(ps, callingUid, userId)) {
25741                return PackageManager.INSTALL_REASON_UNKNOWN;
25742            }
25743            if (ps != null) {
25744                return ps.getInstallReason(userId);
25745            }
25746        }
25747        return PackageManager.INSTALL_REASON_UNKNOWN;
25748    }
25749
25750    @Override
25751    public boolean canRequestPackageInstalls(String packageName, int userId) {
25752        return canRequestPackageInstallsInternal(packageName, 0, userId,
25753                true /* throwIfPermNotDeclared*/);
25754    }
25755
25756    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25757            boolean throwIfPermNotDeclared) {
25758        int callingUid = Binder.getCallingUid();
25759        int uid = getPackageUid(packageName, 0, userId);
25760        if (callingUid != uid && callingUid != Process.ROOT_UID
25761                && callingUid != Process.SYSTEM_UID) {
25762            throw new SecurityException(
25763                    "Caller uid " + callingUid + " does not own package " + packageName);
25764        }
25765        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25766        if (info == null) {
25767            return false;
25768        }
25769        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25770            return false;
25771        }
25772        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25773        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25774        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25775            if (throwIfPermNotDeclared) {
25776                throw new SecurityException("Need to declare " + appOpPermission
25777                        + " to call this api");
25778            } else {
25779                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25780                return false;
25781            }
25782        }
25783        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25784            return false;
25785        }
25786        if (mExternalSourcesPolicy != null) {
25787            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25788            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25789                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25790            }
25791        }
25792        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25793    }
25794
25795    @Override
25796    public ComponentName getInstantAppResolverSettingsComponent() {
25797        return mInstantAppResolverSettingsComponent;
25798    }
25799
25800    @Override
25801    public ComponentName getInstantAppInstallerComponent() {
25802        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25803            return null;
25804        }
25805        return mInstantAppInstallerActivity == null
25806                ? null : mInstantAppInstallerActivity.getComponentName();
25807    }
25808
25809    @Override
25810    public String getInstantAppAndroidId(String packageName, int userId) {
25811        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25812                "getInstantAppAndroidId");
25813        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25814                true /* requireFullPermission */, false /* checkShell */,
25815                "getInstantAppAndroidId");
25816        // Make sure the target is an Instant App.
25817        if (!isInstantApp(packageName, userId)) {
25818            return null;
25819        }
25820        synchronized (mPackages) {
25821            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25822        }
25823    }
25824
25825    boolean canHaveOatDir(String packageName) {
25826        synchronized (mPackages) {
25827            PackageParser.Package p = mPackages.get(packageName);
25828            if (p == null) {
25829                return false;
25830            }
25831            return p.canHaveOatDir();
25832        }
25833    }
25834
25835    private String getOatDir(PackageParser.Package pkg) {
25836        if (!pkg.canHaveOatDir()) {
25837            return null;
25838        }
25839        File codePath = new File(pkg.codePath);
25840        if (codePath.isDirectory()) {
25841            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25842        }
25843        return null;
25844    }
25845
25846    void deleteOatArtifactsOfPackage(String packageName) {
25847        final String[] instructionSets;
25848        final List<String> codePaths;
25849        final String oatDir;
25850        final PackageParser.Package pkg;
25851        synchronized (mPackages) {
25852            pkg = mPackages.get(packageName);
25853        }
25854        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25855        codePaths = pkg.getAllCodePaths();
25856        oatDir = getOatDir(pkg);
25857
25858        for (String codePath : codePaths) {
25859            for (String isa : instructionSets) {
25860                try {
25861                    mInstaller.deleteOdex(codePath, isa, oatDir);
25862                } catch (InstallerException e) {
25863                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25864                }
25865            }
25866        }
25867    }
25868
25869    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25870        Set<String> unusedPackages = new HashSet<>();
25871        long currentTimeInMillis = System.currentTimeMillis();
25872        synchronized (mPackages) {
25873            for (PackageParser.Package pkg : mPackages.values()) {
25874                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25875                if (ps == null) {
25876                    continue;
25877                }
25878                PackageDexUsage.PackageUseInfo packageUseInfo =
25879                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25880                if (PackageManagerServiceUtils
25881                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25882                                downgradeTimeThresholdMillis, packageUseInfo,
25883                                pkg.getLatestPackageUseTimeInMills(),
25884                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25885                    unusedPackages.add(pkg.packageName);
25886                }
25887            }
25888        }
25889        return unusedPackages;
25890    }
25891}
25892
25893interface PackageSender {
25894    void sendPackageBroadcast(final String action, final String pkg,
25895        final Bundle extras, final int flags, final String targetPkg,
25896        final IIntentReceiver finishedReceiver, final int[] userIds);
25897    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25898        boolean includeStopped, int appId, int... userIds);
25899}
25900