PackageManagerService.java revision 52a452cf685c56dc6872dbb19e822736484f672f
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
106
107import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageMoveObserver;
147import android.content.pm.IPackageStatsObserver;
148import android.content.pm.InstantAppInfo;
149import android.content.pm.InstantAppRequest;
150import android.content.pm.InstantAppResolveInfo;
151import android.content.pm.InstrumentationInfo;
152import android.content.pm.IntentFilterVerificationInfo;
153import android.content.pm.KeySet;
154import android.content.pm.PackageCleanItem;
155import android.content.pm.PackageInfo;
156import android.content.pm.PackageInfoLite;
157import android.content.pm.PackageInstaller;
158import android.content.pm.PackageManager;
159import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
160import android.content.pm.PackageManagerInternal;
161import android.content.pm.PackageParser;
162import android.content.pm.PackageParser.ActivityIntentInfo;
163import android.content.pm.PackageParser.PackageLite;
164import android.content.pm.PackageParser.PackageParserException;
165import android.content.pm.PackageStats;
166import android.content.pm.PackageUserState;
167import android.content.pm.ParceledListSlice;
168import android.content.pm.PermissionGroupInfo;
169import android.content.pm.PermissionInfo;
170import android.content.pm.ProviderInfo;
171import android.content.pm.ResolveInfo;
172import android.content.pm.ServiceInfo;
173import android.content.pm.SharedLibraryInfo;
174import android.content.pm.Signature;
175import android.content.pm.UserInfo;
176import android.content.pm.VerifierDeviceIdentity;
177import android.content.pm.VerifierInfo;
178import android.content.pm.VersionedPackage;
179import android.content.res.Resources;
180import android.database.ContentObserver;
181import android.graphics.Bitmap;
182import android.hardware.display.DisplayManager;
183import android.net.Uri;
184import android.os.Binder;
185import android.os.Build;
186import android.os.Bundle;
187import android.os.Debug;
188import android.os.Environment;
189import android.os.Environment.UserEnvironment;
190import android.os.FileUtils;
191import android.os.Handler;
192import android.os.IBinder;
193import android.os.Looper;
194import android.os.Message;
195import android.os.Parcel;
196import android.os.ParcelFileDescriptor;
197import android.os.PatternMatcher;
198import android.os.Process;
199import android.os.RemoteCallbackList;
200import android.os.RemoteException;
201import android.os.ResultReceiver;
202import android.os.SELinux;
203import android.os.ServiceManager;
204import android.os.ShellCallback;
205import android.os.SystemClock;
206import android.os.SystemProperties;
207import android.os.Trace;
208import android.os.UserHandle;
209import android.os.UserManager;
210import android.os.UserManagerInternal;
211import android.os.storage.IStorageManager;
212import android.os.storage.StorageEventListener;
213import android.os.storage.StorageManager;
214import android.os.storage.StorageManagerInternal;
215import android.os.storage.VolumeInfo;
216import android.os.storage.VolumeRecord;
217import android.provider.Settings.Global;
218import android.provider.Settings.Secure;
219import android.security.KeyStore;
220import android.security.SystemKeyStore;
221import android.service.pm.PackageServiceDumpProto;
222import android.system.ErrnoException;
223import android.system.Os;
224import android.text.TextUtils;
225import android.text.format.DateUtils;
226import android.util.ArrayMap;
227import android.util.ArraySet;
228import android.util.Base64;
229import android.util.BootTimingsTraceLog;
230import android.util.DisplayMetrics;
231import android.util.EventLog;
232import android.util.ExceptionUtils;
233import android.util.Log;
234import android.util.LogPrinter;
235import android.util.MathUtils;
236import android.util.PackageUtils;
237import android.util.Pair;
238import android.util.PrintStreamPrinter;
239import android.util.Slog;
240import android.util.SparseArray;
241import android.util.SparseBooleanArray;
242import android.util.SparseIntArray;
243import android.util.Xml;
244import android.util.jar.StrictJarFile;
245import android.util.proto.ProtoOutputStream;
246import android.view.Display;
247
248import com.android.internal.R;
249import com.android.internal.annotations.GuardedBy;
250import com.android.internal.app.IMediaContainerService;
251import com.android.internal.app.ResolverActivity;
252import com.android.internal.content.NativeLibraryHelper;
253import com.android.internal.content.PackageHelper;
254import com.android.internal.logging.MetricsLogger;
255import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
256import com.android.internal.os.IParcelFileDescriptorFactory;
257import com.android.internal.os.RoSystemProperties;
258import com.android.internal.os.SomeArgs;
259import com.android.internal.os.Zygote;
260import com.android.internal.telephony.CarrierAppUtils;
261import com.android.internal.util.ArrayUtils;
262import com.android.internal.util.ConcurrentUtils;
263import com.android.internal.util.DumpUtils;
264import com.android.internal.util.FastPrintWriter;
265import com.android.internal.util.FastXmlSerializer;
266import com.android.internal.util.IndentingPrintWriter;
267import com.android.internal.util.Preconditions;
268import com.android.internal.util.XmlUtils;
269import com.android.server.AttributeCache;
270import com.android.server.DeviceIdleController;
271import com.android.server.EventLogTags;
272import com.android.server.FgThread;
273import com.android.server.IntentResolver;
274import com.android.server.LocalServices;
275import com.android.server.LockGuard;
276import com.android.server.ServiceThread;
277import com.android.server.SystemConfig;
278import com.android.server.SystemServerInitThreadPool;
279import com.android.server.Watchdog;
280import com.android.server.net.NetworkPolicyManagerInternal;
281import com.android.server.pm.Installer.InstallerException;
282import com.android.server.pm.PermissionsState.PermissionState;
283import com.android.server.pm.Settings.DatabaseVersion;
284import com.android.server.pm.Settings.VersionInfo;
285import com.android.server.pm.dex.DexManager;
286import com.android.server.pm.dex.DexoptOptions;
287import com.android.server.pm.dex.PackageDexUsage;
288import com.android.server.storage.DeviceStorageMonitorInternal;
289
290import dalvik.system.CloseGuard;
291import dalvik.system.DexFile;
292import dalvik.system.VMRuntime;
293
294import libcore.io.IoUtils;
295import libcore.io.Streams;
296import libcore.util.EmptyArray;
297
298import org.xmlpull.v1.XmlPullParser;
299import org.xmlpull.v1.XmlPullParserException;
300import org.xmlpull.v1.XmlSerializer;
301
302import java.io.BufferedOutputStream;
303import java.io.BufferedReader;
304import java.io.ByteArrayInputStream;
305import java.io.ByteArrayOutputStream;
306import java.io.File;
307import java.io.FileDescriptor;
308import java.io.FileInputStream;
309import java.io.FileOutputStream;
310import java.io.FileReader;
311import java.io.FilenameFilter;
312import java.io.IOException;
313import java.io.InputStream;
314import java.io.OutputStream;
315import java.io.PrintWriter;
316import java.lang.annotation.Retention;
317import java.lang.annotation.RetentionPolicy;
318import java.nio.charset.StandardCharsets;
319import java.security.DigestInputStream;
320import java.security.MessageDigest;
321import java.security.NoSuchAlgorithmException;
322import java.security.PublicKey;
323import java.security.SecureRandom;
324import java.security.cert.Certificate;
325import java.security.cert.CertificateEncodingException;
326import java.security.cert.CertificateException;
327import java.text.SimpleDateFormat;
328import java.util.ArrayList;
329import java.util.Arrays;
330import java.util.Collection;
331import java.util.Collections;
332import java.util.Comparator;
333import java.util.Date;
334import java.util.HashMap;
335import java.util.HashSet;
336import java.util.Iterator;
337import java.util.List;
338import java.util.Map;
339import java.util.Objects;
340import java.util.Set;
341import java.util.concurrent.CountDownLatch;
342import java.util.concurrent.Future;
343import java.util.concurrent.TimeUnit;
344import java.util.concurrent.atomic.AtomicBoolean;
345import java.util.concurrent.atomic.AtomicInteger;
346import java.util.zip.GZIPInputStream;
347
348/**
349 * Keep track of all those APKs everywhere.
350 * <p>
351 * Internally there are two important locks:
352 * <ul>
353 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
354 * and other related state. It is a fine-grained lock that should only be held
355 * momentarily, as it's one of the most contended locks in the system.
356 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
357 * operations typically involve heavy lifting of application data on disk. Since
358 * {@code installd} is single-threaded, and it's operations can often be slow,
359 * this lock should never be acquired while already holding {@link #mPackages}.
360 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
361 * holding {@link #mInstallLock}.
362 * </ul>
363 * Many internal methods rely on the caller to hold the appropriate locks, and
364 * this contract is expressed through method name suffixes:
365 * <ul>
366 * <li>fooLI(): the caller must hold {@link #mInstallLock}
367 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
368 * being modified must be frozen
369 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
370 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
371 * </ul>
372 * <p>
373 * Because this class is very central to the platform's security; please run all
374 * CTS and unit tests whenever making modifications:
375 *
376 * <pre>
377 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
378 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
379 * </pre>
380 */
381public class PackageManagerService extends IPackageManager.Stub
382        implements PackageSender {
383    static final String TAG = "PackageManager";
384    static final boolean DEBUG_SETTINGS = false;
385    static final boolean DEBUG_PREFERRED = false;
386    static final boolean DEBUG_UPGRADE = false;
387    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
388    private static final boolean DEBUG_BACKUP = false;
389    private static final boolean DEBUG_INSTALL = false;
390    private static final boolean DEBUG_REMOVE = false;
391    private static final boolean DEBUG_BROADCASTS = false;
392    private static final boolean DEBUG_SHOW_INFO = false;
393    private static final boolean DEBUG_PACKAGE_INFO = false;
394    private static final boolean DEBUG_INTENT_MATCHING = false;
395    private static final boolean DEBUG_PACKAGE_SCANNING = false;
396    private static final boolean DEBUG_VERIFY = false;
397    private static final boolean DEBUG_FILTERS = false;
398    private static final boolean DEBUG_PERMISSIONS = false;
399    private static final boolean DEBUG_SHARED_LIBRARIES = false;
400    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
401
402    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
403    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
404    // user, but by default initialize to this.
405    public static final boolean DEBUG_DEXOPT = false;
406
407    private static final boolean DEBUG_ABI_SELECTION = false;
408    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
409    private static final boolean DEBUG_TRIAGED_MISSING = false;
410    private static final boolean DEBUG_APP_DATA = false;
411
412    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
413    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
414
415    private static final boolean HIDE_EPHEMERAL_APIS = false;
416
417    private static final boolean ENABLE_FREE_CACHE_V2 =
418            SystemProperties.getBoolean("fw.free_cache_v2", true);
419
420    private static final int RADIO_UID = Process.PHONE_UID;
421    private static final int LOG_UID = Process.LOG_UID;
422    private static final int NFC_UID = Process.NFC_UID;
423    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
424    private static final int SHELL_UID = Process.SHELL_UID;
425
426    // Cap the size of permission trees that 3rd party apps can define
427    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
428
429    // Suffix used during package installation when copying/moving
430    // package apks to install directory.
431    private static final String INSTALL_PACKAGE_SUFFIX = "-";
432
433    static final int SCAN_NO_DEX = 1<<1;
434    static final int SCAN_FORCE_DEX = 1<<2;
435    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
436    static final int SCAN_NEW_INSTALL = 1<<4;
437    static final int SCAN_UPDATE_TIME = 1<<5;
438    static final int SCAN_BOOTING = 1<<6;
439    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
440    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
441    static final int SCAN_REPLACING = 1<<9;
442    static final int SCAN_REQUIRE_KNOWN = 1<<10;
443    static final int SCAN_MOVE = 1<<11;
444    static final int SCAN_INITIAL = 1<<12;
445    static final int SCAN_CHECK_ONLY = 1<<13;
446    static final int SCAN_DONT_KILL_APP = 1<<14;
447    static final int SCAN_IGNORE_FROZEN = 1<<15;
448    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
449    static final int SCAN_AS_INSTANT_APP = 1<<17;
450    static final int SCAN_AS_FULL_APP = 1<<18;
451    /** Should not be with the scan flags */
452    static final int FLAGS_REMOVE_CHATTY = 1<<31;
453
454    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
455    /** Extension of the compressed packages */
456    private final static String COMPRESSED_EXTENSION = ".gz";
457
458    private static final int[] EMPTY_INT_ARRAY = new int[0];
459
460    private static final int TYPE_UNKNOWN = 0;
461    private static final int TYPE_ACTIVITY = 1;
462    private static final int TYPE_RECEIVER = 2;
463    private static final int TYPE_SERVICE = 3;
464    private static final int TYPE_PROVIDER = 4;
465    @IntDef(prefix = { "TYPE_" }, value = {
466            TYPE_UNKNOWN,
467            TYPE_ACTIVITY,
468            TYPE_RECEIVER,
469            TYPE_SERVICE,
470            TYPE_PROVIDER,
471    })
472    @Retention(RetentionPolicy.SOURCE)
473    public @interface ComponentType {}
474
475    /**
476     * Timeout (in milliseconds) after which the watchdog should declare that
477     * our handler thread is wedged.  The usual default for such things is one
478     * minute but we sometimes do very lengthy I/O operations on this thread,
479     * such as installing multi-gigabyte applications, so ours needs to be longer.
480     */
481    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
482
483    /**
484     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
485     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
486     * settings entry if available, otherwise we use the hardcoded default.  If it's been
487     * more than this long since the last fstrim, we force one during the boot sequence.
488     *
489     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
490     * one gets run at the next available charging+idle time.  This final mandatory
491     * no-fstrim check kicks in only of the other scheduling criteria is never met.
492     */
493    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
494
495    /**
496     * Whether verification is enabled by default.
497     */
498    private static final boolean DEFAULT_VERIFY_ENABLE = true;
499
500    /**
501     * The default maximum time to wait for the verification agent to return in
502     * milliseconds.
503     */
504    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
505
506    /**
507     * The default response for package verification timeout.
508     *
509     * This can be either PackageManager.VERIFICATION_ALLOW or
510     * PackageManager.VERIFICATION_REJECT.
511     */
512    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
513
514    static final String PLATFORM_PACKAGE_NAME = "android";
515
516    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
517
518    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
519            DEFAULT_CONTAINER_PACKAGE,
520            "com.android.defcontainer.DefaultContainerService");
521
522    private static final String KILL_APP_REASON_GIDS_CHANGED =
523            "permission grant or revoke changed gids";
524
525    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
526            "permissions revoked";
527
528    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
529
530    private static final String PACKAGE_SCHEME = "package";
531
532    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
533
534    /** Permission grant: not grant the permission. */
535    private static final int GRANT_DENIED = 1;
536
537    /** Permission grant: grant the permission as an install permission. */
538    private static final int GRANT_INSTALL = 2;
539
540    /** Permission grant: grant the permission as a runtime one. */
541    private static final int GRANT_RUNTIME = 3;
542
543    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
544    private static final int GRANT_UPGRADE = 4;
545
546    /** Canonical intent used to identify what counts as a "web browser" app */
547    private static final Intent sBrowserIntent;
548    static {
549        sBrowserIntent = new Intent();
550        sBrowserIntent.setAction(Intent.ACTION_VIEW);
551        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
552        sBrowserIntent.setData(Uri.parse("http:"));
553    }
554
555    /**
556     * The set of all protected actions [i.e. those actions for which a high priority
557     * intent filter is disallowed].
558     */
559    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
560    static {
561        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
562        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
563        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
564        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
565    }
566
567    // Compilation reasons.
568    public static final int REASON_FIRST_BOOT = 0;
569    public static final int REASON_BOOT = 1;
570    public static final int REASON_INSTALL = 2;
571    public static final int REASON_BACKGROUND_DEXOPT = 3;
572    public static final int REASON_AB_OTA = 4;
573    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
574
575    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
576
577    /** All dangerous permission names in the same order as the events in MetricsEvent */
578    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
579            Manifest.permission.READ_CALENDAR,
580            Manifest.permission.WRITE_CALENDAR,
581            Manifest.permission.CAMERA,
582            Manifest.permission.READ_CONTACTS,
583            Manifest.permission.WRITE_CONTACTS,
584            Manifest.permission.GET_ACCOUNTS,
585            Manifest.permission.ACCESS_FINE_LOCATION,
586            Manifest.permission.ACCESS_COARSE_LOCATION,
587            Manifest.permission.RECORD_AUDIO,
588            Manifest.permission.READ_PHONE_STATE,
589            Manifest.permission.CALL_PHONE,
590            Manifest.permission.READ_CALL_LOG,
591            Manifest.permission.WRITE_CALL_LOG,
592            Manifest.permission.ADD_VOICEMAIL,
593            Manifest.permission.USE_SIP,
594            Manifest.permission.PROCESS_OUTGOING_CALLS,
595            Manifest.permission.READ_CELL_BROADCASTS,
596            Manifest.permission.BODY_SENSORS,
597            Manifest.permission.SEND_SMS,
598            Manifest.permission.RECEIVE_SMS,
599            Manifest.permission.READ_SMS,
600            Manifest.permission.RECEIVE_WAP_PUSH,
601            Manifest.permission.RECEIVE_MMS,
602            Manifest.permission.READ_EXTERNAL_STORAGE,
603            Manifest.permission.WRITE_EXTERNAL_STORAGE,
604            Manifest.permission.READ_PHONE_NUMBERS,
605            Manifest.permission.ANSWER_PHONE_CALLS);
606
607
608    /**
609     * Version number for the package parser cache. Increment this whenever the format or
610     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
611     */
612    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
613
614    /**
615     * Whether the package parser cache is enabled.
616     */
617    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
618
619    final ServiceThread mHandlerThread;
620
621    final PackageHandler mHandler;
622
623    private final ProcessLoggingHandler mProcessLoggingHandler;
624
625    /**
626     * Messages for {@link #mHandler} that need to wait for system ready before
627     * being dispatched.
628     */
629    private ArrayList<Message> mPostSystemReadyMessages;
630
631    final int mSdkVersion = Build.VERSION.SDK_INT;
632
633    final Context mContext;
634    final boolean mFactoryTest;
635    final boolean mOnlyCore;
636    final DisplayMetrics mMetrics;
637    final int mDefParseFlags;
638    final String[] mSeparateProcesses;
639    final boolean mIsUpgrade;
640    final boolean mIsPreNUpgrade;
641    final boolean mIsPreNMR1Upgrade;
642
643    // Have we told the Activity Manager to whitelist the default container service by uid yet?
644    @GuardedBy("mPackages")
645    boolean mDefaultContainerWhitelisted = false;
646
647    @GuardedBy("mPackages")
648    private boolean mDexOptDialogShown;
649
650    /** The location for ASEC container files on internal storage. */
651    final String mAsecInternalPath;
652
653    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
654    // LOCK HELD.  Can be called with mInstallLock held.
655    @GuardedBy("mInstallLock")
656    final Installer mInstaller;
657
658    /** Directory where installed third-party apps stored */
659    final File mAppInstallDir;
660
661    /**
662     * Directory to which applications installed internally have their
663     * 32 bit native libraries copied.
664     */
665    private File mAppLib32InstallDir;
666
667    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
668    // apps.
669    final File mDrmAppPrivateInstallDir;
670
671    // ----------------------------------------------------------------
672
673    // Lock for state used when installing and doing other long running
674    // operations.  Methods that must be called with this lock held have
675    // the suffix "LI".
676    final Object mInstallLock = new Object();
677
678    // ----------------------------------------------------------------
679
680    // Keys are String (package name), values are Package.  This also serves
681    // as the lock for the global state.  Methods that must be called with
682    // this lock held have the prefix "LP".
683    @GuardedBy("mPackages")
684    final ArrayMap<String, PackageParser.Package> mPackages =
685            new ArrayMap<String, PackageParser.Package>();
686
687    final ArrayMap<String, Set<String>> mKnownCodebase =
688            new ArrayMap<String, Set<String>>();
689
690    // Keys are isolated uids and values are the uid of the application
691    // that created the isolated proccess.
692    @GuardedBy("mPackages")
693    final SparseIntArray mIsolatedOwners = new SparseIntArray();
694
695    /**
696     * Tracks new system packages [received in an OTA] that we expect to
697     * find updated user-installed versions. Keys are package name, values
698     * are package location.
699     */
700    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
701    /**
702     * Tracks high priority intent filters for protected actions. During boot, certain
703     * filter actions are protected and should never be allowed to have a high priority
704     * intent filter for them. However, there is one, and only one exception -- the
705     * setup wizard. It must be able to define a high priority intent filter for these
706     * actions to ensure there are no escapes from the wizard. We need to delay processing
707     * of these during boot as we need to look at all of the system packages in order
708     * to know which component is the setup wizard.
709     */
710    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
711    /**
712     * Whether or not processing protected filters should be deferred.
713     */
714    private boolean mDeferProtectedFilters = true;
715
716    /**
717     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
718     */
719    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
720    /**
721     * Whether or not system app permissions should be promoted from install to runtime.
722     */
723    boolean mPromoteSystemApps;
724
725    @GuardedBy("mPackages")
726    final Settings mSettings;
727
728    /**
729     * Set of package names that are currently "frozen", which means active
730     * surgery is being done on the code/data for that package. The platform
731     * will refuse to launch frozen packages to avoid race conditions.
732     *
733     * @see PackageFreezer
734     */
735    @GuardedBy("mPackages")
736    final ArraySet<String> mFrozenPackages = new ArraySet<>();
737
738    final ProtectedPackages mProtectedPackages;
739
740    @GuardedBy("mLoadedVolumes")
741    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
742
743    boolean mFirstBoot;
744
745    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
746
747    // System configuration read by SystemConfig.
748    final int[] mGlobalGids;
749    final SparseArray<ArraySet<String>> mSystemPermissions;
750    @GuardedBy("mAvailableFeatures")
751    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
752
753    // If mac_permissions.xml was found for seinfo labeling.
754    boolean mFoundPolicyFile;
755
756    private final InstantAppRegistry mInstantAppRegistry;
757
758    @GuardedBy("mPackages")
759    int mChangedPackagesSequenceNumber;
760    /**
761     * List of changed [installed, removed or updated] packages.
762     * mapping from user id -> sequence number -> package name
763     */
764    @GuardedBy("mPackages")
765    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
766    /**
767     * The sequence number of the last change to a package.
768     * mapping from user id -> package name -> sequence number
769     */
770    @GuardedBy("mPackages")
771    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
772
773    class PackageParserCallback implements PackageParser.Callback {
774        @Override public final boolean hasFeature(String feature) {
775            return PackageManagerService.this.hasSystemFeature(feature, 0);
776        }
777
778        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
779                Collection<PackageParser.Package> allPackages, String targetPackageName) {
780            List<PackageParser.Package> overlayPackages = null;
781            for (PackageParser.Package p : allPackages) {
782                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
783                    if (overlayPackages == null) {
784                        overlayPackages = new ArrayList<PackageParser.Package>();
785                    }
786                    overlayPackages.add(p);
787                }
788            }
789            if (overlayPackages != null) {
790                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
791                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
792                        return p1.mOverlayPriority - p2.mOverlayPriority;
793                    }
794                };
795                Collections.sort(overlayPackages, cmp);
796            }
797            return overlayPackages;
798        }
799
800        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
801                String targetPackageName, String targetPath) {
802            if ("android".equals(targetPackageName)) {
803                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
804                // native AssetManager.
805                return null;
806            }
807            List<PackageParser.Package> overlayPackages =
808                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
809            if (overlayPackages == null || overlayPackages.isEmpty()) {
810                return null;
811            }
812            List<String> overlayPathList = null;
813            for (PackageParser.Package overlayPackage : overlayPackages) {
814                if (targetPath == null) {
815                    if (overlayPathList == null) {
816                        overlayPathList = new ArrayList<String>();
817                    }
818                    overlayPathList.add(overlayPackage.baseCodePath);
819                    continue;
820                }
821
822                try {
823                    // Creates idmaps for system to parse correctly the Android manifest of the
824                    // target package.
825                    //
826                    // OverlayManagerService will update each of them with a correct gid from its
827                    // target package app id.
828                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
829                            UserHandle.getSharedAppGid(
830                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
831                    if (overlayPathList == null) {
832                        overlayPathList = new ArrayList<String>();
833                    }
834                    overlayPathList.add(overlayPackage.baseCodePath);
835                } catch (InstallerException e) {
836                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
837                            overlayPackage.baseCodePath);
838                }
839            }
840            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
841        }
842
843        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
844            synchronized (mPackages) {
845                return getStaticOverlayPathsLocked(
846                        mPackages.values(), targetPackageName, targetPath);
847            }
848        }
849
850        @Override public final String[] getOverlayApks(String targetPackageName) {
851            return getStaticOverlayPaths(targetPackageName, null);
852        }
853
854        @Override public final String[] getOverlayPaths(String targetPackageName,
855                String targetPath) {
856            return getStaticOverlayPaths(targetPackageName, targetPath);
857        }
858    };
859
860    class ParallelPackageParserCallback extends PackageParserCallback {
861        List<PackageParser.Package> mOverlayPackages = null;
862
863        void findStaticOverlayPackages() {
864            synchronized (mPackages) {
865                for (PackageParser.Package p : mPackages.values()) {
866                    if (p.mIsStaticOverlay) {
867                        if (mOverlayPackages == null) {
868                            mOverlayPackages = new ArrayList<PackageParser.Package>();
869                        }
870                        mOverlayPackages.add(p);
871                    }
872                }
873            }
874        }
875
876        @Override
877        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
878            // We can trust mOverlayPackages without holding mPackages because package uninstall
879            // can't happen while running parallel parsing.
880            // Moreover holding mPackages on each parsing thread causes dead-lock.
881            return mOverlayPackages == null ? null :
882                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
883        }
884    }
885
886    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
887    final ParallelPackageParserCallback mParallelPackageParserCallback =
888            new ParallelPackageParserCallback();
889
890    public static final class SharedLibraryEntry {
891        public final @Nullable String path;
892        public final @Nullable String apk;
893        public final @NonNull SharedLibraryInfo info;
894
895        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
896                String declaringPackageName, int declaringPackageVersionCode) {
897            path = _path;
898            apk = _apk;
899            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
900                    declaringPackageName, declaringPackageVersionCode), null);
901        }
902    }
903
904    // Currently known shared libraries.
905    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
906    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
907            new ArrayMap<>();
908
909    // All available activities, for your resolving pleasure.
910    final ActivityIntentResolver mActivities =
911            new ActivityIntentResolver();
912
913    // All available receivers, for your resolving pleasure.
914    final ActivityIntentResolver mReceivers =
915            new ActivityIntentResolver();
916
917    // All available services, for your resolving pleasure.
918    final ServiceIntentResolver mServices = new ServiceIntentResolver();
919
920    // All available providers, for your resolving pleasure.
921    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
922
923    // Mapping from provider base names (first directory in content URI codePath)
924    // to the provider information.
925    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
926            new ArrayMap<String, PackageParser.Provider>();
927
928    // Mapping from instrumentation class names to info about them.
929    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
930            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
931
932    // Mapping from permission names to info about them.
933    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
934            new ArrayMap<String, PackageParser.PermissionGroup>();
935
936    // Packages whose data we have transfered into another package, thus
937    // should no longer exist.
938    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
939
940    // Broadcast actions that are only available to the system.
941    @GuardedBy("mProtectedBroadcasts")
942    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
943
944    /** List of packages waiting for verification. */
945    final SparseArray<PackageVerificationState> mPendingVerification
946            = new SparseArray<PackageVerificationState>();
947
948    /** Set of packages associated with each app op permission. */
949    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
950
951    final PackageInstallerService mInstallerService;
952
953    private final PackageDexOptimizer mPackageDexOptimizer;
954    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
955    // is used by other apps).
956    private final DexManager mDexManager;
957
958    private AtomicInteger mNextMoveId = new AtomicInteger();
959    private final MoveCallbacks mMoveCallbacks;
960
961    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
962
963    // Cache of users who need badging.
964    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
965
966    /** Token for keys in mPendingVerification. */
967    private int mPendingVerificationToken = 0;
968
969    volatile boolean mSystemReady;
970    volatile boolean mSafeMode;
971    volatile boolean mHasSystemUidErrors;
972    private volatile boolean mEphemeralAppsDisabled;
973
974    ApplicationInfo mAndroidApplication;
975    final ActivityInfo mResolveActivity = new ActivityInfo();
976    final ResolveInfo mResolveInfo = new ResolveInfo();
977    ComponentName mResolveComponentName;
978    PackageParser.Package mPlatformPackage;
979    ComponentName mCustomResolverComponentName;
980
981    boolean mResolverReplaced = false;
982
983    private final @Nullable ComponentName mIntentFilterVerifierComponent;
984    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
985
986    private int mIntentFilterVerificationToken = 0;
987
988    /** The service connection to the ephemeral resolver */
989    final EphemeralResolverConnection mInstantAppResolverConnection;
990    /** Component used to show resolver settings for Instant Apps */
991    final ComponentName mInstantAppResolverSettingsComponent;
992
993    /** Activity used to install instant applications */
994    ActivityInfo mInstantAppInstallerActivity;
995    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
996
997    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
998            = new SparseArray<IntentFilterVerificationState>();
999
1000    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1001
1002    // List of packages names to keep cached, even if they are uninstalled for all users
1003    private List<String> mKeepUninstalledPackages;
1004
1005    private UserManagerInternal mUserManagerInternal;
1006
1007    private DeviceIdleController.LocalService mDeviceIdleController;
1008
1009    private File mCacheDir;
1010
1011    private ArraySet<String> mPrivappPermissionsViolations;
1012
1013    private Future<?> mPrepareAppDataFuture;
1014
1015    private static class IFVerificationParams {
1016        PackageParser.Package pkg;
1017        boolean replacing;
1018        int userId;
1019        int verifierUid;
1020
1021        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1022                int _userId, int _verifierUid) {
1023            pkg = _pkg;
1024            replacing = _replacing;
1025            userId = _userId;
1026            replacing = _replacing;
1027            verifierUid = _verifierUid;
1028        }
1029    }
1030
1031    private interface IntentFilterVerifier<T extends IntentFilter> {
1032        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1033                                               T filter, String packageName);
1034        void startVerifications(int userId);
1035        void receiveVerificationResponse(int verificationId);
1036    }
1037
1038    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1039        private Context mContext;
1040        private ComponentName mIntentFilterVerifierComponent;
1041        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1042
1043        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1044            mContext = context;
1045            mIntentFilterVerifierComponent = verifierComponent;
1046        }
1047
1048        private String getDefaultScheme() {
1049            return IntentFilter.SCHEME_HTTPS;
1050        }
1051
1052        @Override
1053        public void startVerifications(int userId) {
1054            // Launch verifications requests
1055            int count = mCurrentIntentFilterVerifications.size();
1056            for (int n=0; n<count; n++) {
1057                int verificationId = mCurrentIntentFilterVerifications.get(n);
1058                final IntentFilterVerificationState ivs =
1059                        mIntentFilterVerificationStates.get(verificationId);
1060
1061                String packageName = ivs.getPackageName();
1062
1063                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1064                final int filterCount = filters.size();
1065                ArraySet<String> domainsSet = new ArraySet<>();
1066                for (int m=0; m<filterCount; m++) {
1067                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1068                    domainsSet.addAll(filter.getHostsList());
1069                }
1070                synchronized (mPackages) {
1071                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1072                            packageName, domainsSet) != null) {
1073                        scheduleWriteSettingsLocked();
1074                    }
1075                }
1076                sendVerificationRequest(verificationId, ivs);
1077            }
1078            mCurrentIntentFilterVerifications.clear();
1079        }
1080
1081        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1082            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1083            verificationIntent.putExtra(
1084                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1085                    verificationId);
1086            verificationIntent.putExtra(
1087                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1088                    getDefaultScheme());
1089            verificationIntent.putExtra(
1090                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1091                    ivs.getHostsString());
1092            verificationIntent.putExtra(
1093                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1094                    ivs.getPackageName());
1095            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1096            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1097
1098            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1099            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1100                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1101                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1102
1103            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1104            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1105                    "Sending IntentFilter verification broadcast");
1106        }
1107
1108        public void receiveVerificationResponse(int verificationId) {
1109            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1110
1111            final boolean verified = ivs.isVerified();
1112
1113            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1114            final int count = filters.size();
1115            if (DEBUG_DOMAIN_VERIFICATION) {
1116                Slog.i(TAG, "Received verification response " + verificationId
1117                        + " for " + count + " filters, verified=" + verified);
1118            }
1119            for (int n=0; n<count; n++) {
1120                PackageParser.ActivityIntentInfo filter = filters.get(n);
1121                filter.setVerified(verified);
1122
1123                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1124                        + " verified with result:" + verified + " and hosts:"
1125                        + ivs.getHostsString());
1126            }
1127
1128            mIntentFilterVerificationStates.remove(verificationId);
1129
1130            final String packageName = ivs.getPackageName();
1131            IntentFilterVerificationInfo ivi = null;
1132
1133            synchronized (mPackages) {
1134                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1135            }
1136            if (ivi == null) {
1137                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1138                        + verificationId + " packageName:" + packageName);
1139                return;
1140            }
1141            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1142                    "Updating IntentFilterVerificationInfo for package " + packageName
1143                            +" verificationId:" + verificationId);
1144
1145            synchronized (mPackages) {
1146                if (verified) {
1147                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1148                } else {
1149                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1150                }
1151                scheduleWriteSettingsLocked();
1152
1153                final int userId = ivs.getUserId();
1154                if (userId != UserHandle.USER_ALL) {
1155                    final int userStatus =
1156                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1157
1158                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1159                    boolean needUpdate = false;
1160
1161                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1162                    // already been set by the User thru the Disambiguation dialog
1163                    switch (userStatus) {
1164                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1165                            if (verified) {
1166                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1167                            } else {
1168                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1169                            }
1170                            needUpdate = true;
1171                            break;
1172
1173                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1174                            if (verified) {
1175                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1176                                needUpdate = true;
1177                            }
1178                            break;
1179
1180                        default:
1181                            // Nothing to do
1182                    }
1183
1184                    if (needUpdate) {
1185                        mSettings.updateIntentFilterVerificationStatusLPw(
1186                                packageName, updatedStatus, userId);
1187                        scheduleWritePackageRestrictionsLocked(userId);
1188                    }
1189                }
1190            }
1191        }
1192
1193        @Override
1194        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1195                    ActivityIntentInfo filter, String packageName) {
1196            if (!hasValidDomains(filter)) {
1197                return false;
1198            }
1199            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1200            if (ivs == null) {
1201                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1202                        packageName);
1203            }
1204            if (DEBUG_DOMAIN_VERIFICATION) {
1205                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1206            }
1207            ivs.addFilter(filter);
1208            return true;
1209        }
1210
1211        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1212                int userId, int verificationId, String packageName) {
1213            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1214                    verifierUid, userId, packageName);
1215            ivs.setPendingState();
1216            synchronized (mPackages) {
1217                mIntentFilterVerificationStates.append(verificationId, ivs);
1218                mCurrentIntentFilterVerifications.add(verificationId);
1219            }
1220            return ivs;
1221        }
1222    }
1223
1224    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1225        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1226                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1227                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1228    }
1229
1230    // Set of pending broadcasts for aggregating enable/disable of components.
1231    static class PendingPackageBroadcasts {
1232        // for each user id, a map of <package name -> components within that package>
1233        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1234
1235        public PendingPackageBroadcasts() {
1236            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1237        }
1238
1239        public ArrayList<String> get(int userId, String packageName) {
1240            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1241            return packages.get(packageName);
1242        }
1243
1244        public void put(int userId, String packageName, ArrayList<String> components) {
1245            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1246            packages.put(packageName, components);
1247        }
1248
1249        public void remove(int userId, String packageName) {
1250            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1251            if (packages != null) {
1252                packages.remove(packageName);
1253            }
1254        }
1255
1256        public void remove(int userId) {
1257            mUidMap.remove(userId);
1258        }
1259
1260        public int userIdCount() {
1261            return mUidMap.size();
1262        }
1263
1264        public int userIdAt(int n) {
1265            return mUidMap.keyAt(n);
1266        }
1267
1268        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1269            return mUidMap.get(userId);
1270        }
1271
1272        public int size() {
1273            // total number of pending broadcast entries across all userIds
1274            int num = 0;
1275            for (int i = 0; i< mUidMap.size(); i++) {
1276                num += mUidMap.valueAt(i).size();
1277            }
1278            return num;
1279        }
1280
1281        public void clear() {
1282            mUidMap.clear();
1283        }
1284
1285        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1286            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1287            if (map == null) {
1288                map = new ArrayMap<String, ArrayList<String>>();
1289                mUidMap.put(userId, map);
1290            }
1291            return map;
1292        }
1293    }
1294    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1295
1296    // Service Connection to remote media container service to copy
1297    // package uri's from external media onto secure containers
1298    // or internal storage.
1299    private IMediaContainerService mContainerService = null;
1300
1301    static final int SEND_PENDING_BROADCAST = 1;
1302    static final int MCS_BOUND = 3;
1303    static final int END_COPY = 4;
1304    static final int INIT_COPY = 5;
1305    static final int MCS_UNBIND = 6;
1306    static final int START_CLEANING_PACKAGE = 7;
1307    static final int FIND_INSTALL_LOC = 8;
1308    static final int POST_INSTALL = 9;
1309    static final int MCS_RECONNECT = 10;
1310    static final int MCS_GIVE_UP = 11;
1311    static final int UPDATED_MEDIA_STATUS = 12;
1312    static final int WRITE_SETTINGS = 13;
1313    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1314    static final int PACKAGE_VERIFIED = 15;
1315    static final int CHECK_PENDING_VERIFICATION = 16;
1316    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1317    static final int INTENT_FILTER_VERIFIED = 18;
1318    static final int WRITE_PACKAGE_LIST = 19;
1319    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1320
1321    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1322
1323    // Delay time in millisecs
1324    static final int BROADCAST_DELAY = 10 * 1000;
1325
1326    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1327            2 * 60 * 60 * 1000L; /* two hours */
1328
1329    static UserManagerService sUserManager;
1330
1331    // Stores a list of users whose package restrictions file needs to be updated
1332    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1333
1334    final private DefaultContainerConnection mDefContainerConn =
1335            new DefaultContainerConnection();
1336    class DefaultContainerConnection implements ServiceConnection {
1337        public void onServiceConnected(ComponentName name, IBinder service) {
1338            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1339            final IMediaContainerService imcs = IMediaContainerService.Stub
1340                    .asInterface(Binder.allowBlocking(service));
1341            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1342        }
1343
1344        public void onServiceDisconnected(ComponentName name) {
1345            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1346        }
1347    }
1348
1349    // Recordkeeping of restore-after-install operations that are currently in flight
1350    // between the Package Manager and the Backup Manager
1351    static class PostInstallData {
1352        public InstallArgs args;
1353        public PackageInstalledInfo res;
1354
1355        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1356            args = _a;
1357            res = _r;
1358        }
1359    }
1360
1361    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1362    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1363
1364    // XML tags for backup/restore of various bits of state
1365    private static final String TAG_PREFERRED_BACKUP = "pa";
1366    private static final String TAG_DEFAULT_APPS = "da";
1367    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1368
1369    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1370    private static final String TAG_ALL_GRANTS = "rt-grants";
1371    private static final String TAG_GRANT = "grant";
1372    private static final String ATTR_PACKAGE_NAME = "pkg";
1373
1374    private static final String TAG_PERMISSION = "perm";
1375    private static final String ATTR_PERMISSION_NAME = "name";
1376    private static final String ATTR_IS_GRANTED = "g";
1377    private static final String ATTR_USER_SET = "set";
1378    private static final String ATTR_USER_FIXED = "fixed";
1379    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1380
1381    // System/policy permission grants are not backed up
1382    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1383            FLAG_PERMISSION_POLICY_FIXED
1384            | FLAG_PERMISSION_SYSTEM_FIXED
1385            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1386
1387    // And we back up these user-adjusted states
1388    private static final int USER_RUNTIME_GRANT_MASK =
1389            FLAG_PERMISSION_USER_SET
1390            | FLAG_PERMISSION_USER_FIXED
1391            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1392
1393    final @Nullable String mRequiredVerifierPackage;
1394    final @NonNull String mRequiredInstallerPackage;
1395    final @NonNull String mRequiredUninstallerPackage;
1396    final @Nullable String mSetupWizardPackage;
1397    final @Nullable String mStorageManagerPackage;
1398    final @NonNull String mServicesSystemSharedLibraryPackageName;
1399    final @NonNull String mSharedSystemSharedLibraryPackageName;
1400
1401    final boolean mPermissionReviewRequired;
1402
1403    private final PackageUsage mPackageUsage = new PackageUsage();
1404    private final CompilerStats mCompilerStats = new CompilerStats();
1405
1406    class PackageHandler extends Handler {
1407        private boolean mBound = false;
1408        final ArrayList<HandlerParams> mPendingInstalls =
1409            new ArrayList<HandlerParams>();
1410
1411        private boolean connectToService() {
1412            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1413                    " DefaultContainerService");
1414            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1416            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1417                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1418                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1419                mBound = true;
1420                return true;
1421            }
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1423            return false;
1424        }
1425
1426        private void disconnectService() {
1427            mContainerService = null;
1428            mBound = false;
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1430            mContext.unbindService(mDefContainerConn);
1431            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1432        }
1433
1434        PackageHandler(Looper looper) {
1435            super(looper);
1436        }
1437
1438        public void handleMessage(Message msg) {
1439            try {
1440                doHandleMessage(msg);
1441            } finally {
1442                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1443            }
1444        }
1445
1446        void doHandleMessage(Message msg) {
1447            switch (msg.what) {
1448                case INIT_COPY: {
1449                    HandlerParams params = (HandlerParams) msg.obj;
1450                    int idx = mPendingInstalls.size();
1451                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1452                    // If a bind was already initiated we dont really
1453                    // need to do anything. The pending install
1454                    // will be processed later on.
1455                    if (!mBound) {
1456                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1457                                System.identityHashCode(mHandler));
1458                        // If this is the only one pending we might
1459                        // have to bind to the service again.
1460                        if (!connectToService()) {
1461                            Slog.e(TAG, "Failed to bind to media container service");
1462                            params.serviceError();
1463                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1464                                    System.identityHashCode(mHandler));
1465                            if (params.traceMethod != null) {
1466                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1467                                        params.traceCookie);
1468                            }
1469                            return;
1470                        } else {
1471                            // Once we bind to the service, the first
1472                            // pending request will be processed.
1473                            mPendingInstalls.add(idx, params);
1474                        }
1475                    } else {
1476                        mPendingInstalls.add(idx, params);
1477                        // Already bound to the service. Just make
1478                        // sure we trigger off processing the first request.
1479                        if (idx == 0) {
1480                            mHandler.sendEmptyMessage(MCS_BOUND);
1481                        }
1482                    }
1483                    break;
1484                }
1485                case MCS_BOUND: {
1486                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1487                    if (msg.obj != null) {
1488                        mContainerService = (IMediaContainerService) msg.obj;
1489                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1490                                System.identityHashCode(mHandler));
1491                    }
1492                    if (mContainerService == null) {
1493                        if (!mBound) {
1494                            // Something seriously wrong since we are not bound and we are not
1495                            // waiting for connection. Bail out.
1496                            Slog.e(TAG, "Cannot bind to media container service");
1497                            for (HandlerParams params : mPendingInstalls) {
1498                                // Indicate service bind error
1499                                params.serviceError();
1500                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1501                                        System.identityHashCode(params));
1502                                if (params.traceMethod != null) {
1503                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1504                                            params.traceMethod, params.traceCookie);
1505                                }
1506                                return;
1507                            }
1508                            mPendingInstalls.clear();
1509                        } else {
1510                            Slog.w(TAG, "Waiting to connect to media container service");
1511                        }
1512                    } else if (mPendingInstalls.size() > 0) {
1513                        HandlerParams params = mPendingInstalls.get(0);
1514                        if (params != null) {
1515                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1516                                    System.identityHashCode(params));
1517                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1518                            if (params.startCopy()) {
1519                                // We are done...  look for more work or to
1520                                // go idle.
1521                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1522                                        "Checking for more work or unbind...");
1523                                // Delete pending install
1524                                if (mPendingInstalls.size() > 0) {
1525                                    mPendingInstalls.remove(0);
1526                                }
1527                                if (mPendingInstalls.size() == 0) {
1528                                    if (mBound) {
1529                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1530                                                "Posting delayed MCS_UNBIND");
1531                                        removeMessages(MCS_UNBIND);
1532                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1533                                        // Unbind after a little delay, to avoid
1534                                        // continual thrashing.
1535                                        sendMessageDelayed(ubmsg, 10000);
1536                                    }
1537                                } else {
1538                                    // There are more pending requests in queue.
1539                                    // Just post MCS_BOUND message to trigger processing
1540                                    // of next pending install.
1541                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1542                                            "Posting MCS_BOUND for next work");
1543                                    mHandler.sendEmptyMessage(MCS_BOUND);
1544                                }
1545                            }
1546                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1547                        }
1548                    } else {
1549                        // Should never happen ideally.
1550                        Slog.w(TAG, "Empty queue");
1551                    }
1552                    break;
1553                }
1554                case MCS_RECONNECT: {
1555                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1556                    if (mPendingInstalls.size() > 0) {
1557                        if (mBound) {
1558                            disconnectService();
1559                        }
1560                        if (!connectToService()) {
1561                            Slog.e(TAG, "Failed to bind to media container service");
1562                            for (HandlerParams params : mPendingInstalls) {
1563                                // Indicate service bind error
1564                                params.serviceError();
1565                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1566                                        System.identityHashCode(params));
1567                            }
1568                            mPendingInstalls.clear();
1569                        }
1570                    }
1571                    break;
1572                }
1573                case MCS_UNBIND: {
1574                    // If there is no actual work left, then time to unbind.
1575                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1576
1577                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1578                        if (mBound) {
1579                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1580
1581                            disconnectService();
1582                        }
1583                    } else if (mPendingInstalls.size() > 0) {
1584                        // There are more pending requests in queue.
1585                        // Just post MCS_BOUND message to trigger processing
1586                        // of next pending install.
1587                        mHandler.sendEmptyMessage(MCS_BOUND);
1588                    }
1589
1590                    break;
1591                }
1592                case MCS_GIVE_UP: {
1593                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1594                    HandlerParams params = mPendingInstalls.remove(0);
1595                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1596                            System.identityHashCode(params));
1597                    break;
1598                }
1599                case SEND_PENDING_BROADCAST: {
1600                    String packages[];
1601                    ArrayList<String> components[];
1602                    int size = 0;
1603                    int uids[];
1604                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1605                    synchronized (mPackages) {
1606                        if (mPendingBroadcasts == null) {
1607                            return;
1608                        }
1609                        size = mPendingBroadcasts.size();
1610                        if (size <= 0) {
1611                            // Nothing to be done. Just return
1612                            return;
1613                        }
1614                        packages = new String[size];
1615                        components = new ArrayList[size];
1616                        uids = new int[size];
1617                        int i = 0;  // filling out the above arrays
1618
1619                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1620                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1621                            Iterator<Map.Entry<String, ArrayList<String>>> it
1622                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1623                                            .entrySet().iterator();
1624                            while (it.hasNext() && i < size) {
1625                                Map.Entry<String, ArrayList<String>> ent = it.next();
1626                                packages[i] = ent.getKey();
1627                                components[i] = ent.getValue();
1628                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1629                                uids[i] = (ps != null)
1630                                        ? UserHandle.getUid(packageUserId, ps.appId)
1631                                        : -1;
1632                                i++;
1633                            }
1634                        }
1635                        size = i;
1636                        mPendingBroadcasts.clear();
1637                    }
1638                    // Send broadcasts
1639                    for (int i = 0; i < size; i++) {
1640                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1641                    }
1642                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1643                    break;
1644                }
1645                case START_CLEANING_PACKAGE: {
1646                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1647                    final String packageName = (String)msg.obj;
1648                    final int userId = msg.arg1;
1649                    final boolean andCode = msg.arg2 != 0;
1650                    synchronized (mPackages) {
1651                        if (userId == UserHandle.USER_ALL) {
1652                            int[] users = sUserManager.getUserIds();
1653                            for (int user : users) {
1654                                mSettings.addPackageToCleanLPw(
1655                                        new PackageCleanItem(user, packageName, andCode));
1656                            }
1657                        } else {
1658                            mSettings.addPackageToCleanLPw(
1659                                    new PackageCleanItem(userId, packageName, andCode));
1660                        }
1661                    }
1662                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1663                    startCleaningPackages();
1664                } break;
1665                case POST_INSTALL: {
1666                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1667
1668                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1669                    final boolean didRestore = (msg.arg2 != 0);
1670                    mRunningInstalls.delete(msg.arg1);
1671
1672                    if (data != null) {
1673                        InstallArgs args = data.args;
1674                        PackageInstalledInfo parentRes = data.res;
1675
1676                        final boolean grantPermissions = (args.installFlags
1677                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1678                        final boolean killApp = (args.installFlags
1679                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1680                        final boolean virtualPreload = ((args.installFlags
1681                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1682                        final String[] grantedPermissions = args.installGrantPermissions;
1683
1684                        // Handle the parent package
1685                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1686                                virtualPreload, grantedPermissions, didRestore,
1687                                args.installerPackageName, args.observer);
1688
1689                        // Handle the child packages
1690                        final int childCount = (parentRes.addedChildPackages != null)
1691                                ? parentRes.addedChildPackages.size() : 0;
1692                        for (int i = 0; i < childCount; i++) {
1693                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1694                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1695                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1696                                    args.installerPackageName, args.observer);
1697                        }
1698
1699                        // Log tracing if needed
1700                        if (args.traceMethod != null) {
1701                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1702                                    args.traceCookie);
1703                        }
1704                    } else {
1705                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1706                    }
1707
1708                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1709                } break;
1710                case UPDATED_MEDIA_STATUS: {
1711                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1712                    boolean reportStatus = msg.arg1 == 1;
1713                    boolean doGc = msg.arg2 == 1;
1714                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1715                    if (doGc) {
1716                        // Force a gc to clear up stale containers.
1717                        Runtime.getRuntime().gc();
1718                    }
1719                    if (msg.obj != null) {
1720                        @SuppressWarnings("unchecked")
1721                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1722                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1723                        // Unload containers
1724                        unloadAllContainers(args);
1725                    }
1726                    if (reportStatus) {
1727                        try {
1728                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1729                                    "Invoking StorageManagerService call back");
1730                            PackageHelper.getStorageManager().finishMediaUpdate();
1731                        } catch (RemoteException e) {
1732                            Log.e(TAG, "StorageManagerService not running?");
1733                        }
1734                    }
1735                } break;
1736                case WRITE_SETTINGS: {
1737                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1738                    synchronized (mPackages) {
1739                        removeMessages(WRITE_SETTINGS);
1740                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1741                        mSettings.writeLPr();
1742                        mDirtyUsers.clear();
1743                    }
1744                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1745                } break;
1746                case WRITE_PACKAGE_RESTRICTIONS: {
1747                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1748                    synchronized (mPackages) {
1749                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1750                        for (int userId : mDirtyUsers) {
1751                            mSettings.writePackageRestrictionsLPr(userId);
1752                        }
1753                        mDirtyUsers.clear();
1754                    }
1755                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1756                } break;
1757                case WRITE_PACKAGE_LIST: {
1758                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1759                    synchronized (mPackages) {
1760                        removeMessages(WRITE_PACKAGE_LIST);
1761                        mSettings.writePackageListLPr(msg.arg1);
1762                    }
1763                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1764                } break;
1765                case CHECK_PENDING_VERIFICATION: {
1766                    final int verificationId = msg.arg1;
1767                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1768
1769                    if ((state != null) && !state.timeoutExtended()) {
1770                        final InstallArgs args = state.getInstallArgs();
1771                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1772
1773                        Slog.i(TAG, "Verification timed out for " + originUri);
1774                        mPendingVerification.remove(verificationId);
1775
1776                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1777
1778                        final UserHandle user = args.getUser();
1779                        if (getDefaultVerificationResponse(user)
1780                                == PackageManager.VERIFICATION_ALLOW) {
1781                            Slog.i(TAG, "Continuing with installation of " + originUri);
1782                            state.setVerifierResponse(Binder.getCallingUid(),
1783                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1784                            broadcastPackageVerified(verificationId, originUri,
1785                                    PackageManager.VERIFICATION_ALLOW, user);
1786                            try {
1787                                ret = args.copyApk(mContainerService, true);
1788                            } catch (RemoteException e) {
1789                                Slog.e(TAG, "Could not contact the ContainerService");
1790                            }
1791                        } else {
1792                            broadcastPackageVerified(verificationId, originUri,
1793                                    PackageManager.VERIFICATION_REJECT, user);
1794                        }
1795
1796                        Trace.asyncTraceEnd(
1797                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1798
1799                        processPendingInstall(args, ret);
1800                        mHandler.sendEmptyMessage(MCS_UNBIND);
1801                    }
1802                    break;
1803                }
1804                case PACKAGE_VERIFIED: {
1805                    final int verificationId = msg.arg1;
1806
1807                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1808                    if (state == null) {
1809                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1810                        break;
1811                    }
1812
1813                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1814
1815                    state.setVerifierResponse(response.callerUid, response.code);
1816
1817                    if (state.isVerificationComplete()) {
1818                        mPendingVerification.remove(verificationId);
1819
1820                        final InstallArgs args = state.getInstallArgs();
1821                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1822
1823                        int ret;
1824                        if (state.isInstallAllowed()) {
1825                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1826                            broadcastPackageVerified(verificationId, originUri,
1827                                    response.code, state.getInstallArgs().getUser());
1828                            try {
1829                                ret = args.copyApk(mContainerService, true);
1830                            } catch (RemoteException e) {
1831                                Slog.e(TAG, "Could not contact the ContainerService");
1832                            }
1833                        } else {
1834                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1835                        }
1836
1837                        Trace.asyncTraceEnd(
1838                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1839
1840                        processPendingInstall(args, ret);
1841                        mHandler.sendEmptyMessage(MCS_UNBIND);
1842                    }
1843
1844                    break;
1845                }
1846                case START_INTENT_FILTER_VERIFICATIONS: {
1847                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1848                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1849                            params.replacing, params.pkg);
1850                    break;
1851                }
1852                case INTENT_FILTER_VERIFIED: {
1853                    final int verificationId = msg.arg1;
1854
1855                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1856                            verificationId);
1857                    if (state == null) {
1858                        Slog.w(TAG, "Invalid IntentFilter verification token "
1859                                + verificationId + " received");
1860                        break;
1861                    }
1862
1863                    final int userId = state.getUserId();
1864
1865                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1866                            "Processing IntentFilter verification with token:"
1867                            + verificationId + " and userId:" + userId);
1868
1869                    final IntentFilterVerificationResponse response =
1870                            (IntentFilterVerificationResponse) msg.obj;
1871
1872                    state.setVerifierResponse(response.callerUid, response.code);
1873
1874                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1875                            "IntentFilter verification with token:" + verificationId
1876                            + " and userId:" + userId
1877                            + " is settings verifier response with response code:"
1878                            + response.code);
1879
1880                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1881                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1882                                + response.getFailedDomainsString());
1883                    }
1884
1885                    if (state.isVerificationComplete()) {
1886                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1887                    } else {
1888                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1889                                "IntentFilter verification with token:" + verificationId
1890                                + " was not said to be complete");
1891                    }
1892
1893                    break;
1894                }
1895                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1896                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1897                            mInstantAppResolverConnection,
1898                            (InstantAppRequest) msg.obj,
1899                            mInstantAppInstallerActivity,
1900                            mHandler);
1901                }
1902            }
1903        }
1904    }
1905
1906    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1907            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1908            boolean launchedForRestore, String installerPackage,
1909            IPackageInstallObserver2 installObserver) {
1910        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1911            // Send the removed broadcasts
1912            if (res.removedInfo != null) {
1913                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1914            }
1915
1916            // Now that we successfully installed the package, grant runtime
1917            // permissions if requested before broadcasting the install. Also
1918            // for legacy apps in permission review mode we clear the permission
1919            // review flag which is used to emulate runtime permissions for
1920            // legacy apps.
1921            if (grantPermissions) {
1922                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1923            }
1924
1925            final boolean update = res.removedInfo != null
1926                    && res.removedInfo.removedPackage != null;
1927            final String origInstallerPackageName = res.removedInfo != null
1928                    ? res.removedInfo.installerPackageName : null;
1929
1930            // If this is the first time we have child packages for a disabled privileged
1931            // app that had no children, we grant requested runtime permissions to the new
1932            // children if the parent on the system image had them already granted.
1933            if (res.pkg.parentPackage != null) {
1934                synchronized (mPackages) {
1935                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1936                }
1937            }
1938
1939            synchronized (mPackages) {
1940                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1941            }
1942
1943            final String packageName = res.pkg.applicationInfo.packageName;
1944
1945            // Determine the set of users who are adding this package for
1946            // the first time vs. those who are seeing an update.
1947            int[] firstUsers = EMPTY_INT_ARRAY;
1948            int[] updateUsers = EMPTY_INT_ARRAY;
1949            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1950            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1951            for (int newUser : res.newUsers) {
1952                if (ps.getInstantApp(newUser)) {
1953                    continue;
1954                }
1955                if (allNewUsers) {
1956                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1957                    continue;
1958                }
1959                boolean isNew = true;
1960                for (int origUser : res.origUsers) {
1961                    if (origUser == newUser) {
1962                        isNew = false;
1963                        break;
1964                    }
1965                }
1966                if (isNew) {
1967                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1968                } else {
1969                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1970                }
1971            }
1972
1973            // Send installed broadcasts if the package is not a static shared lib.
1974            if (res.pkg.staticSharedLibName == null) {
1975                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1976
1977                // Send added for users that see the package for the first time
1978                // sendPackageAddedForNewUsers also deals with system apps
1979                int appId = UserHandle.getAppId(res.uid);
1980                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1981                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1982                        virtualPreload /*startReceiver*/, appId, firstUsers);
1983
1984                // Send added for users that don't see the package for the first time
1985                Bundle extras = new Bundle(1);
1986                extras.putInt(Intent.EXTRA_UID, res.uid);
1987                if (update) {
1988                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1989                }
1990                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1991                        extras, 0 /*flags*/,
1992                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1993                if (origInstallerPackageName != null) {
1994                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1995                            extras, 0 /*flags*/,
1996                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1997                }
1998
1999                // Send replaced for users that don't see the package for the first time
2000                if (update) {
2001                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2002                            packageName, extras, 0 /*flags*/,
2003                            null /*targetPackage*/, null /*finishedReceiver*/,
2004                            updateUsers);
2005                    if (origInstallerPackageName != null) {
2006                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2007                                extras, 0 /*flags*/,
2008                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
2009                    }
2010                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2011                            null /*package*/, null /*extras*/, 0 /*flags*/,
2012                            packageName /*targetPackage*/,
2013                            null /*finishedReceiver*/, updateUsers);
2014                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2015                    // First-install and we did a restore, so we're responsible for the
2016                    // first-launch broadcast.
2017                    if (DEBUG_BACKUP) {
2018                        Slog.i(TAG, "Post-restore of " + packageName
2019                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2020                    }
2021                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2022                }
2023
2024                // Send broadcast package appeared if forward locked/external for all users
2025                // treat asec-hosted packages like removable media on upgrade
2026                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2027                    if (DEBUG_INSTALL) {
2028                        Slog.i(TAG, "upgrading pkg " + res.pkg
2029                                + " is ASEC-hosted -> AVAILABLE");
2030                    }
2031                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2032                    ArrayList<String> pkgList = new ArrayList<>(1);
2033                    pkgList.add(packageName);
2034                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2035                }
2036            }
2037
2038            // Work that needs to happen on first install within each user
2039            if (firstUsers != null && firstUsers.length > 0) {
2040                synchronized (mPackages) {
2041                    for (int userId : firstUsers) {
2042                        // If this app is a browser and it's newly-installed for some
2043                        // users, clear any default-browser state in those users. The
2044                        // app's nature doesn't depend on the user, so we can just check
2045                        // its browser nature in any user and generalize.
2046                        if (packageIsBrowser(packageName, userId)) {
2047                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2048                        }
2049
2050                        // We may also need to apply pending (restored) runtime
2051                        // permission grants within these users.
2052                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2053                    }
2054                }
2055            }
2056
2057            // Log current value of "unknown sources" setting
2058            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2059                    getUnknownSourcesSettings());
2060
2061            // Remove the replaced package's older resources safely now
2062            // We delete after a gc for applications  on sdcard.
2063            if (res.removedInfo != null && res.removedInfo.args != null) {
2064                Runtime.getRuntime().gc();
2065                synchronized (mInstallLock) {
2066                    res.removedInfo.args.doPostDeleteLI(true);
2067                }
2068            } else {
2069                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2070                // and not block here.
2071                VMRuntime.getRuntime().requestConcurrentGC();
2072            }
2073
2074            // Notify DexManager that the package was installed for new users.
2075            // The updated users should already be indexed and the package code paths
2076            // should not change.
2077            // Don't notify the manager for ephemeral apps as they are not expected to
2078            // survive long enough to benefit of background optimizations.
2079            for (int userId : firstUsers) {
2080                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2081                // There's a race currently where some install events may interleave with an uninstall.
2082                // This can lead to package info being null (b/36642664).
2083                if (info != null) {
2084                    mDexManager.notifyPackageInstalled(info, userId);
2085                }
2086            }
2087        }
2088
2089        // If someone is watching installs - notify them
2090        if (installObserver != null) {
2091            try {
2092                Bundle extras = extrasForInstallResult(res);
2093                installObserver.onPackageInstalled(res.name, res.returnCode,
2094                        res.returnMsg, extras);
2095            } catch (RemoteException e) {
2096                Slog.i(TAG, "Observer no longer exists.");
2097            }
2098        }
2099    }
2100
2101    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2102            PackageParser.Package pkg) {
2103        if (pkg.parentPackage == null) {
2104            return;
2105        }
2106        if (pkg.requestedPermissions == null) {
2107            return;
2108        }
2109        final PackageSetting disabledSysParentPs = mSettings
2110                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2111        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2112                || !disabledSysParentPs.isPrivileged()
2113                || (disabledSysParentPs.childPackageNames != null
2114                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2115            return;
2116        }
2117        final int[] allUserIds = sUserManager.getUserIds();
2118        final int permCount = pkg.requestedPermissions.size();
2119        for (int i = 0; i < permCount; i++) {
2120            String permission = pkg.requestedPermissions.get(i);
2121            BasePermission bp = mSettings.mPermissions.get(permission);
2122            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2123                continue;
2124            }
2125            for (int userId : allUserIds) {
2126                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2127                        permission, userId)) {
2128                    grantRuntimePermission(pkg.packageName, permission, userId);
2129                }
2130            }
2131        }
2132    }
2133
2134    private StorageEventListener mStorageListener = new StorageEventListener() {
2135        @Override
2136        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2137            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2138                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2139                    final String volumeUuid = vol.getFsUuid();
2140
2141                    // Clean up any users or apps that were removed or recreated
2142                    // while this volume was missing
2143                    sUserManager.reconcileUsers(volumeUuid);
2144                    reconcileApps(volumeUuid);
2145
2146                    // Clean up any install sessions that expired or were
2147                    // cancelled while this volume was missing
2148                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2149
2150                    loadPrivatePackages(vol);
2151
2152                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2153                    unloadPrivatePackages(vol);
2154                }
2155            }
2156
2157            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2158                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2159                    updateExternalMediaStatus(true, false);
2160                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2161                    updateExternalMediaStatus(false, false);
2162                }
2163            }
2164        }
2165
2166        @Override
2167        public void onVolumeForgotten(String fsUuid) {
2168            if (TextUtils.isEmpty(fsUuid)) {
2169                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2170                return;
2171            }
2172
2173            // Remove any apps installed on the forgotten volume
2174            synchronized (mPackages) {
2175                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2176                for (PackageSetting ps : packages) {
2177                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2178                    deletePackageVersioned(new VersionedPackage(ps.name,
2179                            PackageManager.VERSION_CODE_HIGHEST),
2180                            new LegacyPackageDeleteObserver(null).getBinder(),
2181                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2182                    // Try very hard to release any references to this package
2183                    // so we don't risk the system server being killed due to
2184                    // open FDs
2185                    AttributeCache.instance().removePackage(ps.name);
2186                }
2187
2188                mSettings.onVolumeForgotten(fsUuid);
2189                mSettings.writeLPr();
2190            }
2191        }
2192    };
2193
2194    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2195            String[] grantedPermissions) {
2196        for (int userId : userIds) {
2197            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2198        }
2199    }
2200
2201    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2202            String[] grantedPermissions) {
2203        PackageSetting ps = (PackageSetting) pkg.mExtras;
2204        if (ps == null) {
2205            return;
2206        }
2207
2208        PermissionsState permissionsState = ps.getPermissionsState();
2209
2210        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2211                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2212
2213        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2214                >= Build.VERSION_CODES.M;
2215
2216        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2217
2218        for (String permission : pkg.requestedPermissions) {
2219            final BasePermission bp;
2220            synchronized (mPackages) {
2221                bp = mSettings.mPermissions.get(permission);
2222            }
2223            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2224                    && (!instantApp || bp.isInstant())
2225                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2226                    && (grantedPermissions == null
2227                           || ArrayUtils.contains(grantedPermissions, permission))) {
2228                final int flags = permissionsState.getPermissionFlags(permission, userId);
2229                if (supportsRuntimePermissions) {
2230                    // Installer cannot change immutable permissions.
2231                    if ((flags & immutableFlags) == 0) {
2232                        grantRuntimePermission(pkg.packageName, permission, userId);
2233                    }
2234                } else if (mPermissionReviewRequired) {
2235                    // In permission review mode we clear the review flag when we
2236                    // are asked to install the app with all permissions granted.
2237                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2238                        updatePermissionFlags(permission, pkg.packageName,
2239                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2240                    }
2241                }
2242            }
2243        }
2244    }
2245
2246    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2247        Bundle extras = null;
2248        switch (res.returnCode) {
2249            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2250                extras = new Bundle();
2251                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2252                        res.origPermission);
2253                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2254                        res.origPackage);
2255                break;
2256            }
2257            case PackageManager.INSTALL_SUCCEEDED: {
2258                extras = new Bundle();
2259                extras.putBoolean(Intent.EXTRA_REPLACING,
2260                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2261                break;
2262            }
2263        }
2264        return extras;
2265    }
2266
2267    void scheduleWriteSettingsLocked() {
2268        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2269            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2270        }
2271    }
2272
2273    void scheduleWritePackageListLocked(int userId) {
2274        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2275            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2276            msg.arg1 = userId;
2277            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2278        }
2279    }
2280
2281    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2282        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2283        scheduleWritePackageRestrictionsLocked(userId);
2284    }
2285
2286    void scheduleWritePackageRestrictionsLocked(int userId) {
2287        final int[] userIds = (userId == UserHandle.USER_ALL)
2288                ? sUserManager.getUserIds() : new int[]{userId};
2289        for (int nextUserId : userIds) {
2290            if (!sUserManager.exists(nextUserId)) return;
2291            mDirtyUsers.add(nextUserId);
2292            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2293                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2294            }
2295        }
2296    }
2297
2298    public static PackageManagerService main(Context context, Installer installer,
2299            boolean factoryTest, boolean onlyCore) {
2300        // Self-check for initial settings.
2301        PackageManagerServiceCompilerMapping.checkProperties();
2302
2303        PackageManagerService m = new PackageManagerService(context, installer,
2304                factoryTest, onlyCore);
2305        m.enableSystemUserPackages();
2306        ServiceManager.addService("package", m);
2307        return m;
2308    }
2309
2310    private void enableSystemUserPackages() {
2311        if (!UserManager.isSplitSystemUser()) {
2312            return;
2313        }
2314        // For system user, enable apps based on the following conditions:
2315        // - app is whitelisted or belong to one of these groups:
2316        //   -- system app which has no launcher icons
2317        //   -- system app which has INTERACT_ACROSS_USERS permission
2318        //   -- system IME app
2319        // - app is not in the blacklist
2320        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2321        Set<String> enableApps = new ArraySet<>();
2322        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2323                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2324                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2325        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2326        enableApps.addAll(wlApps);
2327        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2328                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2329        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2330        enableApps.removeAll(blApps);
2331        Log.i(TAG, "Applications installed for system user: " + enableApps);
2332        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2333                UserHandle.SYSTEM);
2334        final int allAppsSize = allAps.size();
2335        synchronized (mPackages) {
2336            for (int i = 0; i < allAppsSize; i++) {
2337                String pName = allAps.get(i);
2338                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2339                // Should not happen, but we shouldn't be failing if it does
2340                if (pkgSetting == null) {
2341                    continue;
2342                }
2343                boolean install = enableApps.contains(pName);
2344                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2345                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2346                            + " for system user");
2347                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2348                }
2349            }
2350            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2351        }
2352    }
2353
2354    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2355        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2356                Context.DISPLAY_SERVICE);
2357        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2358    }
2359
2360    /**
2361     * Requests that files preopted on a secondary system partition be copied to the data partition
2362     * if possible.  Note that the actual copying of the files is accomplished by init for security
2363     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2364     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2365     */
2366    private static void requestCopyPreoptedFiles() {
2367        final int WAIT_TIME_MS = 100;
2368        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2369        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2370            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2371            // We will wait for up to 100 seconds.
2372            final long timeStart = SystemClock.uptimeMillis();
2373            final long timeEnd = timeStart + 100 * 1000;
2374            long timeNow = timeStart;
2375            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2376                try {
2377                    Thread.sleep(WAIT_TIME_MS);
2378                } catch (InterruptedException e) {
2379                    // Do nothing
2380                }
2381                timeNow = SystemClock.uptimeMillis();
2382                if (timeNow > timeEnd) {
2383                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2384                    Slog.wtf(TAG, "cppreopt did not finish!");
2385                    break;
2386                }
2387            }
2388
2389            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2390        }
2391    }
2392
2393    public PackageManagerService(Context context, Installer installer,
2394            boolean factoryTest, boolean onlyCore) {
2395        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2396        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2397        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2398                SystemClock.uptimeMillis());
2399
2400        if (mSdkVersion <= 0) {
2401            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2402        }
2403
2404        mContext = context;
2405
2406        mPermissionReviewRequired = context.getResources().getBoolean(
2407                R.bool.config_permissionReviewRequired);
2408
2409        mFactoryTest = factoryTest;
2410        mOnlyCore = onlyCore;
2411        mMetrics = new DisplayMetrics();
2412        mSettings = new Settings(mPackages);
2413        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2414                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2415        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2416                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2417        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2418                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2419        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2420                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2421        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2422                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2423        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2424                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2425
2426        String separateProcesses = SystemProperties.get("debug.separate_processes");
2427        if (separateProcesses != null && separateProcesses.length() > 0) {
2428            if ("*".equals(separateProcesses)) {
2429                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2430                mSeparateProcesses = null;
2431                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2432            } else {
2433                mDefParseFlags = 0;
2434                mSeparateProcesses = separateProcesses.split(",");
2435                Slog.w(TAG, "Running with debug.separate_processes: "
2436                        + separateProcesses);
2437            }
2438        } else {
2439            mDefParseFlags = 0;
2440            mSeparateProcesses = null;
2441        }
2442
2443        mInstaller = installer;
2444        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2445                "*dexopt*");
2446        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2447        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2448
2449        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2450                FgThread.get().getLooper());
2451
2452        getDefaultDisplayMetrics(context, mMetrics);
2453
2454        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2455        SystemConfig systemConfig = SystemConfig.getInstance();
2456        mGlobalGids = systemConfig.getGlobalGids();
2457        mSystemPermissions = systemConfig.getSystemPermissions();
2458        mAvailableFeatures = systemConfig.getAvailableFeatures();
2459        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2460
2461        mProtectedPackages = new ProtectedPackages(mContext);
2462
2463        synchronized (mInstallLock) {
2464        // writer
2465        synchronized (mPackages) {
2466            mHandlerThread = new ServiceThread(TAG,
2467                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2468            mHandlerThread.start();
2469            mHandler = new PackageHandler(mHandlerThread.getLooper());
2470            mProcessLoggingHandler = new ProcessLoggingHandler();
2471            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2472
2473            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2474            mInstantAppRegistry = new InstantAppRegistry(this);
2475
2476            File dataDir = Environment.getDataDirectory();
2477            mAppInstallDir = new File(dataDir, "app");
2478            mAppLib32InstallDir = new File(dataDir, "app-lib");
2479            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2480            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2481            sUserManager = new UserManagerService(context, this,
2482                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2483
2484            // Propagate permission configuration in to package manager.
2485            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2486                    = systemConfig.getPermissions();
2487            for (int i=0; i<permConfig.size(); i++) {
2488                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2489                BasePermission bp = mSettings.mPermissions.get(perm.name);
2490                if (bp == null) {
2491                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2492                    mSettings.mPermissions.put(perm.name, bp);
2493                }
2494                if (perm.gids != null) {
2495                    bp.setGids(perm.gids, perm.perUser);
2496                }
2497            }
2498
2499            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2500            final int builtInLibCount = libConfig.size();
2501            for (int i = 0; i < builtInLibCount; i++) {
2502                String name = libConfig.keyAt(i);
2503                String path = libConfig.valueAt(i);
2504                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2505                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2506            }
2507
2508            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2509
2510            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2511            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2512            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2513
2514            // Clean up orphaned packages for which the code path doesn't exist
2515            // and they are an update to a system app - caused by bug/32321269
2516            final int packageSettingCount = mSettings.mPackages.size();
2517            for (int i = packageSettingCount - 1; i >= 0; i--) {
2518                PackageSetting ps = mSettings.mPackages.valueAt(i);
2519                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2520                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2521                    mSettings.mPackages.removeAt(i);
2522                    mSettings.enableSystemPackageLPw(ps.name);
2523                }
2524            }
2525
2526            if (mFirstBoot) {
2527                requestCopyPreoptedFiles();
2528            }
2529
2530            String customResolverActivity = Resources.getSystem().getString(
2531                    R.string.config_customResolverActivity);
2532            if (TextUtils.isEmpty(customResolverActivity)) {
2533                customResolverActivity = null;
2534            } else {
2535                mCustomResolverComponentName = ComponentName.unflattenFromString(
2536                        customResolverActivity);
2537            }
2538
2539            long startTime = SystemClock.uptimeMillis();
2540
2541            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2542                    startTime);
2543
2544            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2545            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2546
2547            if (bootClassPath == null) {
2548                Slog.w(TAG, "No BOOTCLASSPATH found!");
2549            }
2550
2551            if (systemServerClassPath == null) {
2552                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2553            }
2554
2555            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2556
2557            final VersionInfo ver = mSettings.getInternalVersion();
2558            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2559            if (mIsUpgrade) {
2560                logCriticalInfo(Log.INFO,
2561                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2562            }
2563
2564            // when upgrading from pre-M, promote system app permissions from install to runtime
2565            mPromoteSystemApps =
2566                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2567
2568            // When upgrading from pre-N, we need to handle package extraction like first boot,
2569            // as there is no profiling data available.
2570            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2571
2572            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2573
2574            // save off the names of pre-existing system packages prior to scanning; we don't
2575            // want to automatically grant runtime permissions for new system apps
2576            if (mPromoteSystemApps) {
2577                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2578                while (pkgSettingIter.hasNext()) {
2579                    PackageSetting ps = pkgSettingIter.next();
2580                    if (isSystemApp(ps)) {
2581                        mExistingSystemPackages.add(ps.name);
2582                    }
2583                }
2584            }
2585
2586            mCacheDir = preparePackageParserCache(mIsUpgrade);
2587
2588            // Set flag to monitor and not change apk file paths when
2589            // scanning install directories.
2590            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2591
2592            if (mIsUpgrade || mFirstBoot) {
2593                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2594            }
2595
2596            // Collect vendor overlay packages. (Do this before scanning any apps.)
2597            // For security and version matching reason, only consider
2598            // overlay packages if they reside in the right directory.
2599            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2600                    | PackageParser.PARSE_IS_SYSTEM
2601                    | PackageParser.PARSE_IS_SYSTEM_DIR
2602                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2603
2604            mParallelPackageParserCallback.findStaticOverlayPackages();
2605
2606            // Find base frameworks (resource packages without code).
2607            scanDirTracedLI(frameworkDir, mDefParseFlags
2608                    | PackageParser.PARSE_IS_SYSTEM
2609                    | PackageParser.PARSE_IS_SYSTEM_DIR
2610                    | PackageParser.PARSE_IS_PRIVILEGED,
2611                    scanFlags | SCAN_NO_DEX, 0);
2612
2613            // Collected privileged system packages.
2614            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2615            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2616                    | PackageParser.PARSE_IS_SYSTEM
2617                    | PackageParser.PARSE_IS_SYSTEM_DIR
2618                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2619
2620            // Collect ordinary system packages.
2621            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2622            scanDirTracedLI(systemAppDir, mDefParseFlags
2623                    | PackageParser.PARSE_IS_SYSTEM
2624                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2625
2626            // Collect all vendor packages.
2627            File vendorAppDir = new File("/vendor/app");
2628            try {
2629                vendorAppDir = vendorAppDir.getCanonicalFile();
2630            } catch (IOException e) {
2631                // failed to look up canonical path, continue with original one
2632            }
2633            scanDirTracedLI(vendorAppDir, mDefParseFlags
2634                    | PackageParser.PARSE_IS_SYSTEM
2635                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2636
2637            // Collect all OEM packages.
2638            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2639            scanDirTracedLI(oemAppDir, mDefParseFlags
2640                    | PackageParser.PARSE_IS_SYSTEM
2641                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2642
2643            // Prune any system packages that no longer exist.
2644            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2645            // Stub packages must either be replaced with full versions in the /data
2646            // partition or be disabled.
2647            final List<String> stubSystemApps = new ArrayList<>();
2648            if (!mOnlyCore) {
2649                // do this first before mucking with mPackages for the "expecting better" case
2650                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2651                while (pkgIterator.hasNext()) {
2652                    final PackageParser.Package pkg = pkgIterator.next();
2653                    if (pkg.isStub) {
2654                        stubSystemApps.add(pkg.packageName);
2655                    }
2656                }
2657
2658                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2659                while (psit.hasNext()) {
2660                    PackageSetting ps = psit.next();
2661
2662                    /*
2663                     * If this is not a system app, it can't be a
2664                     * disable system app.
2665                     */
2666                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2667                        continue;
2668                    }
2669
2670                    /*
2671                     * If the package is scanned, it's not erased.
2672                     */
2673                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2674                    if (scannedPkg != null) {
2675                        /*
2676                         * If the system app is both scanned and in the
2677                         * disabled packages list, then it must have been
2678                         * added via OTA. Remove it from the currently
2679                         * scanned package so the previously user-installed
2680                         * application can be scanned.
2681                         */
2682                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2683                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2684                                    + ps.name + "; removing system app.  Last known codePath="
2685                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2686                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2687                                    + scannedPkg.mVersionCode);
2688                            removePackageLI(scannedPkg, true);
2689                            mExpectingBetter.put(ps.name, ps.codePath);
2690                        }
2691
2692                        continue;
2693                    }
2694
2695                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2696                        psit.remove();
2697                        logCriticalInfo(Log.WARN, "System package " + ps.name
2698                                + " no longer exists; it's data will be wiped");
2699                        // Actual deletion of code and data will be handled by later
2700                        // reconciliation step
2701                    } else {
2702                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2703                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2704                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2705                        }
2706                    }
2707                }
2708            }
2709
2710            //look for any incomplete package installations
2711            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2712            for (int i = 0; i < deletePkgsList.size(); i++) {
2713                // Actual deletion of code and data will be handled by later
2714                // reconciliation step
2715                final String packageName = deletePkgsList.get(i).name;
2716                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2717                synchronized (mPackages) {
2718                    mSettings.removePackageLPw(packageName);
2719                }
2720            }
2721
2722            //delete tmp files
2723            deleteTempPackageFiles();
2724
2725            // Remove any shared userIDs that have no associated packages
2726            mSettings.pruneSharedUsersLPw();
2727            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2728            final int systemPackagesCount = mPackages.size();
2729            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2730                    + " ms, packageCount: " + systemPackagesCount
2731                    + " ms, timePerPackage: "
2732                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount));
2733            if (mIsUpgrade && systemPackagesCount > 0) {
2734                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2735                        ((int) systemScanTime) / systemPackagesCount);
2736            }
2737            if (!mOnlyCore) {
2738                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2739                        SystemClock.uptimeMillis());
2740                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2741
2742                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2743                        | PackageParser.PARSE_FORWARD_LOCK,
2744                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2745
2746                // Remove disable package settings for updated system apps that were
2747                // removed via an OTA. If the update is no longer present, remove the
2748                // app completely. Otherwise, revoke their system privileges.
2749                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2750                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2751                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2752
2753                    final String msg;
2754                    if (deletedPkg == null) {
2755                        // should have found an update, but, we didn't; remove everything
2756                        msg = "Updated system package " + deletedAppName
2757                                + " no longer exists; removing its data";
2758                        // Actual deletion of code and data will be handled by later
2759                        // reconciliation step
2760                    } else {
2761                        // found an update; revoke system privileges
2762                        msg = "Updated system package + " + deletedAppName
2763                                + " no longer exists; revoking system privileges";
2764
2765                        // Don't do anything if a stub is removed from the system image. If
2766                        // we were to remove the uncompressed version from the /data partition,
2767                        // this is where it'd be done.
2768
2769                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2770                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2771                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2772                    }
2773                    logCriticalInfo(Log.WARN, msg);
2774                }
2775
2776                /*
2777                 * Make sure all system apps that we expected to appear on
2778                 * the userdata partition actually showed up. If they never
2779                 * appeared, crawl back and revive the system version.
2780                 */
2781                for (int i = 0; i < mExpectingBetter.size(); i++) {
2782                    final String packageName = mExpectingBetter.keyAt(i);
2783                    if (!mPackages.containsKey(packageName)) {
2784                        final File scanFile = mExpectingBetter.valueAt(i);
2785
2786                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2787                                + " but never showed up; reverting to system");
2788
2789                        int reparseFlags = mDefParseFlags;
2790                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2791                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2792                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2793                                    | PackageParser.PARSE_IS_PRIVILEGED;
2794                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2795                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2796                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2797                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2798                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2799                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2800                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2801                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2802                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2803                        } else {
2804                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2805                            continue;
2806                        }
2807
2808                        mSettings.enableSystemPackageLPw(packageName);
2809
2810                        try {
2811                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2812                        } catch (PackageManagerException e) {
2813                            Slog.e(TAG, "Failed to parse original system package: "
2814                                    + e.getMessage());
2815                        }
2816                    }
2817                }
2818
2819                // Uncompress and install any stubbed system applications.
2820                // This must be done last to ensure all stubs are replaced or disabled.
2821                decompressSystemApplications(stubSystemApps, scanFlags);
2822
2823                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2824                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2825                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2826                        + " ms, packageCount: " + dataPackagesCount
2827                        + " ms, timePerPackage: "
2828                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount));
2829                if (mIsUpgrade && dataPackagesCount > 0) {
2830                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2831                            ((int) dataScanTime) / dataPackagesCount);
2832                }
2833            }
2834            mExpectingBetter.clear();
2835
2836            // Resolve the storage manager.
2837            mStorageManagerPackage = getStorageManagerPackageName();
2838
2839            // Resolve protected action filters. Only the setup wizard is allowed to
2840            // have a high priority filter for these actions.
2841            mSetupWizardPackage = getSetupWizardPackageName();
2842            if (mProtectedFilters.size() > 0) {
2843                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2844                    Slog.i(TAG, "No setup wizard;"
2845                        + " All protected intents capped to priority 0");
2846                }
2847                for (ActivityIntentInfo filter : mProtectedFilters) {
2848                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2849                        if (DEBUG_FILTERS) {
2850                            Slog.i(TAG, "Found setup wizard;"
2851                                + " allow priority " + filter.getPriority() + ";"
2852                                + " package: " + filter.activity.info.packageName
2853                                + " activity: " + filter.activity.className
2854                                + " priority: " + filter.getPriority());
2855                        }
2856                        // skip setup wizard; allow it to keep the high priority filter
2857                        continue;
2858                    }
2859                    if (DEBUG_FILTERS) {
2860                        Slog.i(TAG, "Protected action; cap priority to 0;"
2861                                + " package: " + filter.activity.info.packageName
2862                                + " activity: " + filter.activity.className
2863                                + " origPrio: " + filter.getPriority());
2864                    }
2865                    filter.setPriority(0);
2866                }
2867            }
2868            mDeferProtectedFilters = false;
2869            mProtectedFilters.clear();
2870
2871            // Now that we know all of the shared libraries, update all clients to have
2872            // the correct library paths.
2873            updateAllSharedLibrariesLPw(null);
2874
2875            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2876                // NOTE: We ignore potential failures here during a system scan (like
2877                // the rest of the commands above) because there's precious little we
2878                // can do about it. A settings error is reported, though.
2879                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2880            }
2881
2882            // Now that we know all the packages we are keeping,
2883            // read and update their last usage times.
2884            mPackageUsage.read(mPackages);
2885            mCompilerStats.read();
2886
2887            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2888                    SystemClock.uptimeMillis());
2889            Slog.i(TAG, "Time to scan packages: "
2890                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2891                    + " seconds");
2892
2893            // If the platform SDK has changed since the last time we booted,
2894            // we need to re-grant app permission to catch any new ones that
2895            // appear.  This is really a hack, and means that apps can in some
2896            // cases get permissions that the user didn't initially explicitly
2897            // allow...  it would be nice to have some better way to handle
2898            // this situation.
2899            int updateFlags = UPDATE_PERMISSIONS_ALL;
2900            if (ver.sdkVersion != mSdkVersion) {
2901                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2902                        + mSdkVersion + "; regranting permissions for internal storage");
2903                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2904            }
2905            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2906            ver.sdkVersion = mSdkVersion;
2907
2908            // If this is the first boot or an update from pre-M, and it is a normal
2909            // boot, then we need to initialize the default preferred apps across
2910            // all defined users.
2911            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2912                for (UserInfo user : sUserManager.getUsers(true)) {
2913                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2914                    applyFactoryDefaultBrowserLPw(user.id);
2915                    primeDomainVerificationsLPw(user.id);
2916                }
2917            }
2918
2919            // Prepare storage for system user really early during boot,
2920            // since core system apps like SettingsProvider and SystemUI
2921            // can't wait for user to start
2922            final int storageFlags;
2923            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2924                storageFlags = StorageManager.FLAG_STORAGE_DE;
2925            } else {
2926                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2927            }
2928            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2929                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2930                    true /* onlyCoreApps */);
2931            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2932                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2933                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2934                traceLog.traceBegin("AppDataFixup");
2935                try {
2936                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2937                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2938                } catch (InstallerException e) {
2939                    Slog.w(TAG, "Trouble fixing GIDs", e);
2940                }
2941                traceLog.traceEnd();
2942
2943                traceLog.traceBegin("AppDataPrepare");
2944                if (deferPackages == null || deferPackages.isEmpty()) {
2945                    return;
2946                }
2947                int count = 0;
2948                for (String pkgName : deferPackages) {
2949                    PackageParser.Package pkg = null;
2950                    synchronized (mPackages) {
2951                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2952                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2953                            pkg = ps.pkg;
2954                        }
2955                    }
2956                    if (pkg != null) {
2957                        synchronized (mInstallLock) {
2958                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2959                                    true /* maybeMigrateAppData */);
2960                        }
2961                        count++;
2962                    }
2963                }
2964                traceLog.traceEnd();
2965                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2966            }, "prepareAppData");
2967
2968            // If this is first boot after an OTA, and a normal boot, then
2969            // we need to clear code cache directories.
2970            // Note that we do *not* clear the application profiles. These remain valid
2971            // across OTAs and are used to drive profile verification (post OTA) and
2972            // profile compilation (without waiting to collect a fresh set of profiles).
2973            if (mIsUpgrade && !onlyCore) {
2974                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2975                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2976                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2977                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2978                        // No apps are running this early, so no need to freeze
2979                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2980                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2981                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2982                    }
2983                }
2984                ver.fingerprint = Build.FINGERPRINT;
2985            }
2986
2987            checkDefaultBrowser();
2988
2989            // clear only after permissions and other defaults have been updated
2990            mExistingSystemPackages.clear();
2991            mPromoteSystemApps = false;
2992
2993            // All the changes are done during package scanning.
2994            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2995
2996            // can downgrade to reader
2997            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2998            mSettings.writeLPr();
2999            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3000            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3001                    SystemClock.uptimeMillis());
3002
3003            if (!mOnlyCore) {
3004                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3005                mRequiredInstallerPackage = getRequiredInstallerLPr();
3006                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3007                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3008                if (mIntentFilterVerifierComponent != null) {
3009                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3010                            mIntentFilterVerifierComponent);
3011                } else {
3012                    mIntentFilterVerifier = null;
3013                }
3014                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3015                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3016                        SharedLibraryInfo.VERSION_UNDEFINED);
3017                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3018                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3019                        SharedLibraryInfo.VERSION_UNDEFINED);
3020            } else {
3021                mRequiredVerifierPackage = null;
3022                mRequiredInstallerPackage = null;
3023                mRequiredUninstallerPackage = null;
3024                mIntentFilterVerifierComponent = null;
3025                mIntentFilterVerifier = null;
3026                mServicesSystemSharedLibraryPackageName = null;
3027                mSharedSystemSharedLibraryPackageName = null;
3028            }
3029
3030            mInstallerService = new PackageInstallerService(context, this);
3031            final Pair<ComponentName, String> instantAppResolverComponent =
3032                    getInstantAppResolverLPr();
3033            if (instantAppResolverComponent != null) {
3034                if (DEBUG_EPHEMERAL) {
3035                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3036                }
3037                mInstantAppResolverConnection = new EphemeralResolverConnection(
3038                        mContext, instantAppResolverComponent.first,
3039                        instantAppResolverComponent.second);
3040                mInstantAppResolverSettingsComponent =
3041                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3042            } else {
3043                mInstantAppResolverConnection = null;
3044                mInstantAppResolverSettingsComponent = null;
3045            }
3046            updateInstantAppInstallerLocked(null);
3047
3048            // Read and update the usage of dex files.
3049            // Do this at the end of PM init so that all the packages have their
3050            // data directory reconciled.
3051            // At this point we know the code paths of the packages, so we can validate
3052            // the disk file and build the internal cache.
3053            // The usage file is expected to be small so loading and verifying it
3054            // should take a fairly small time compare to the other activities (e.g. package
3055            // scanning).
3056            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3057            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3058            for (int userId : currentUserIds) {
3059                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3060            }
3061            mDexManager.load(userPackages);
3062            if (mIsUpgrade) {
3063                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3064                        (int) (SystemClock.uptimeMillis() - startTime));
3065            }
3066        } // synchronized (mPackages)
3067        } // synchronized (mInstallLock)
3068
3069        // Now after opening every single application zip, make sure they
3070        // are all flushed.  Not really needed, but keeps things nice and
3071        // tidy.
3072        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3073        Runtime.getRuntime().gc();
3074        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3075
3076        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3077        FallbackCategoryProvider.loadFallbacks();
3078        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3079
3080        // The initial scanning above does many calls into installd while
3081        // holding the mPackages lock, but we're mostly interested in yelling
3082        // once we have a booted system.
3083        mInstaller.setWarnIfHeld(mPackages);
3084
3085        // Expose private service for system components to use.
3086        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3087        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3088    }
3089
3090    /**
3091     * Uncompress and install stub applications.
3092     * <p>In order to save space on the system partition, some applications are shipped in a
3093     * compressed form. In addition the compressed bits for the full application, the
3094     * system image contains a tiny stub comprised of only the Android manifest.
3095     * <p>During the first boot, attempt to uncompress and install the full application. If
3096     * the application can't be installed for any reason, disable the stub and prevent
3097     * uncompressing the full application during future boots.
3098     * <p>In order to forcefully attempt an installation of a full application, go to app
3099     * settings and enable the application.
3100     */
3101    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3102        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3103            final String pkgName = stubSystemApps.get(i);
3104            // skip if the system package is already disabled
3105            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3106                stubSystemApps.remove(i);
3107                continue;
3108            }
3109            // skip if the package isn't installed (?!); this should never happen
3110            final PackageParser.Package pkg = mPackages.get(pkgName);
3111            if (pkg == null) {
3112                stubSystemApps.remove(i);
3113                continue;
3114            }
3115            // skip if the package has been disabled by the user
3116            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3117            if (ps != null) {
3118                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3119                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3120                    stubSystemApps.remove(i);
3121                    continue;
3122                }
3123            }
3124
3125            if (DEBUG_COMPRESSION) {
3126                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3127            }
3128
3129            // uncompress the binary to its eventual destination on /data
3130            final File scanFile = decompressPackage(pkg);
3131            if (scanFile == null) {
3132                continue;
3133            }
3134
3135            // install the package to replace the stub on /system
3136            try {
3137                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3138                removePackageLI(pkg, true /*chatty*/);
3139                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3140                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3141                        UserHandle.USER_SYSTEM, "android");
3142                stubSystemApps.remove(i);
3143                continue;
3144            } catch (PackageManagerException e) {
3145                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3146            }
3147
3148            // any failed attempt to install the package will be cleaned up later
3149        }
3150
3151        // disable any stub still left; these failed to install the full application
3152        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3153            final String pkgName = stubSystemApps.get(i);
3154            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3155            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3156                    UserHandle.USER_SYSTEM, "android");
3157            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3158        }
3159    }
3160
3161    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3162        if (DEBUG_COMPRESSION) {
3163            Slog.i(TAG, "Decompress file"
3164                    + "; src: " + srcFile.getAbsolutePath()
3165                    + ", dst: " + dstFile.getAbsolutePath());
3166        }
3167        try (
3168                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3169                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3170        ) {
3171            Streams.copy(fileIn, fileOut);
3172            Os.chmod(dstFile.getAbsolutePath(), 0644);
3173            return PackageManager.INSTALL_SUCCEEDED;
3174        } catch (IOException e) {
3175            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3176                    + "; src: " + srcFile.getAbsolutePath()
3177                    + ", dst: " + dstFile.getAbsolutePath());
3178        }
3179        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3180    }
3181
3182    private File[] getCompressedFiles(String codePath) {
3183        return new File(codePath).listFiles(new FilenameFilter() {
3184            @Override
3185            public boolean accept(File dir, String name) {
3186                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3187            }
3188        });
3189    }
3190
3191    private boolean compressedFileExists(String codePath) {
3192        final File[] compressedFiles = getCompressedFiles(codePath);
3193        return compressedFiles != null && compressedFiles.length > 0;
3194    }
3195
3196    /**
3197     * Decompresses the given package on the system image onto
3198     * the /data partition.
3199     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3200     */
3201    private File decompressPackage(PackageParser.Package pkg) {
3202        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3203        if (compressedFiles == null || compressedFiles.length == 0) {
3204            if (DEBUG_COMPRESSION) {
3205                Slog.i(TAG, "No files to decompress");
3206            }
3207            return null;
3208        }
3209        final File dstCodePath =
3210                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3211        int ret = PackageManager.INSTALL_SUCCEEDED;
3212        try {
3213            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3214            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3215            for (File srcFile : compressedFiles) {
3216                final String srcFileName = srcFile.getName();
3217                final String dstFileName = srcFileName.substring(
3218                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3219                final File dstFile = new File(dstCodePath, dstFileName);
3220                ret = decompressFile(srcFile, dstFile);
3221                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3222                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3223                            + "; pkg: " + pkg.packageName
3224                            + ", file: " + dstFileName);
3225                    break;
3226                }
3227            }
3228        } catch (ErrnoException e) {
3229            logCriticalInfo(Log.ERROR, "Failed to decompress"
3230                    + "; pkg: " + pkg.packageName
3231                    + ", err: " + e.errno);
3232        }
3233        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3234            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3235            NativeLibraryHelper.Handle handle = null;
3236            try {
3237                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3238                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3239                        null /*abiOverride*/);
3240            } catch (IOException e) {
3241                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3242                        + "; pkg: " + pkg.packageName);
3243                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3244            } finally {
3245                IoUtils.closeQuietly(handle);
3246            }
3247        }
3248        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3249            if (dstCodePath == null || !dstCodePath.exists()) {
3250                return null;
3251            }
3252            removeCodePathLI(dstCodePath);
3253            return null;
3254        }
3255        return dstCodePath;
3256    }
3257
3258    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3259        // we're only interested in updating the installer appliction when 1) it's not
3260        // already set or 2) the modified package is the installer
3261        if (mInstantAppInstallerActivity != null
3262                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3263                        .equals(modifiedPackage)) {
3264            return;
3265        }
3266        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3267    }
3268
3269    private static File preparePackageParserCache(boolean isUpgrade) {
3270        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3271            return null;
3272        }
3273
3274        // Disable package parsing on eng builds to allow for faster incremental development.
3275        if (Build.IS_ENG) {
3276            return null;
3277        }
3278
3279        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3280            Slog.i(TAG, "Disabling package parser cache due to system property.");
3281            return null;
3282        }
3283
3284        // The base directory for the package parser cache lives under /data/system/.
3285        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3286                "package_cache");
3287        if (cacheBaseDir == null) {
3288            return null;
3289        }
3290
3291        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3292        // This also serves to "GC" unused entries when the package cache version changes (which
3293        // can only happen during upgrades).
3294        if (isUpgrade) {
3295            FileUtils.deleteContents(cacheBaseDir);
3296        }
3297
3298
3299        // Return the versioned package cache directory. This is something like
3300        // "/data/system/package_cache/1"
3301        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3302
3303        // The following is a workaround to aid development on non-numbered userdebug
3304        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3305        // the system partition is newer.
3306        //
3307        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3308        // that starts with "eng." to signify that this is an engineering build and not
3309        // destined for release.
3310        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3311            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3312
3313            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3314            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3315            // in general and should not be used for production changes. In this specific case,
3316            // we know that they will work.
3317            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3318            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3319                FileUtils.deleteContents(cacheBaseDir);
3320                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3321            }
3322        }
3323
3324        return cacheDir;
3325    }
3326
3327    @Override
3328    public boolean isFirstBoot() {
3329        // allow instant applications
3330        return mFirstBoot;
3331    }
3332
3333    @Override
3334    public boolean isOnlyCoreApps() {
3335        // allow instant applications
3336        return mOnlyCore;
3337    }
3338
3339    @Override
3340    public boolean isUpgrade() {
3341        // allow instant applications
3342        return mIsUpgrade;
3343    }
3344
3345    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3346        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3347
3348        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3349                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3350                UserHandle.USER_SYSTEM);
3351        if (matches.size() == 1) {
3352            return matches.get(0).getComponentInfo().packageName;
3353        } else if (matches.size() == 0) {
3354            Log.e(TAG, "There should probably be a verifier, but, none were found");
3355            return null;
3356        }
3357        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3358    }
3359
3360    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3361        synchronized (mPackages) {
3362            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3363            if (libraryEntry == null) {
3364                throw new IllegalStateException("Missing required shared library:" + name);
3365            }
3366            return libraryEntry.apk;
3367        }
3368    }
3369
3370    private @NonNull String getRequiredInstallerLPr() {
3371        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3372        intent.addCategory(Intent.CATEGORY_DEFAULT);
3373        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3374
3375        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3376                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3377                UserHandle.USER_SYSTEM);
3378        if (matches.size() == 1) {
3379            ResolveInfo resolveInfo = matches.get(0);
3380            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3381                throw new RuntimeException("The installer must be a privileged app");
3382            }
3383            return matches.get(0).getComponentInfo().packageName;
3384        } else {
3385            throw new RuntimeException("There must be exactly one installer; found " + matches);
3386        }
3387    }
3388
3389    private @NonNull String getRequiredUninstallerLPr() {
3390        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3391        intent.addCategory(Intent.CATEGORY_DEFAULT);
3392        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3393
3394        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3395                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3396                UserHandle.USER_SYSTEM);
3397        if (resolveInfo == null ||
3398                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3399            throw new RuntimeException("There must be exactly one uninstaller; found "
3400                    + resolveInfo);
3401        }
3402        return resolveInfo.getComponentInfo().packageName;
3403    }
3404
3405    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3406        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3407
3408        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3409                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3410                UserHandle.USER_SYSTEM);
3411        ResolveInfo best = null;
3412        final int N = matches.size();
3413        for (int i = 0; i < N; i++) {
3414            final ResolveInfo cur = matches.get(i);
3415            final String packageName = cur.getComponentInfo().packageName;
3416            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3417                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3418                continue;
3419            }
3420
3421            if (best == null || cur.priority > best.priority) {
3422                best = cur;
3423            }
3424        }
3425
3426        if (best != null) {
3427            return best.getComponentInfo().getComponentName();
3428        }
3429        Slog.w(TAG, "Intent filter verifier not found");
3430        return null;
3431    }
3432
3433    @Override
3434    public @Nullable ComponentName getInstantAppResolverComponent() {
3435        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3436            return null;
3437        }
3438        synchronized (mPackages) {
3439            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3440            if (instantAppResolver == null) {
3441                return null;
3442            }
3443            return instantAppResolver.first;
3444        }
3445    }
3446
3447    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3448        final String[] packageArray =
3449                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3450        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3451            if (DEBUG_EPHEMERAL) {
3452                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3453            }
3454            return null;
3455        }
3456
3457        final int callingUid = Binder.getCallingUid();
3458        final int resolveFlags =
3459                MATCH_DIRECT_BOOT_AWARE
3460                | MATCH_DIRECT_BOOT_UNAWARE
3461                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3462        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3463        final Intent resolverIntent = new Intent(actionName);
3464        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3465                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3466        // temporarily look for the old action
3467        if (resolvers.size() == 0) {
3468            if (DEBUG_EPHEMERAL) {
3469                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3470            }
3471            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3472            resolverIntent.setAction(actionName);
3473            resolvers = queryIntentServicesInternal(resolverIntent, null,
3474                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3475        }
3476        final int N = resolvers.size();
3477        if (N == 0) {
3478            if (DEBUG_EPHEMERAL) {
3479                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3480            }
3481            return null;
3482        }
3483
3484        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3485        for (int i = 0; i < N; i++) {
3486            final ResolveInfo info = resolvers.get(i);
3487
3488            if (info.serviceInfo == null) {
3489                continue;
3490            }
3491
3492            final String packageName = info.serviceInfo.packageName;
3493            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3494                if (DEBUG_EPHEMERAL) {
3495                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3496                            + " pkg: " + packageName + ", info:" + info);
3497                }
3498                continue;
3499            }
3500
3501            if (DEBUG_EPHEMERAL) {
3502                Slog.v(TAG, "Ephemeral resolver found;"
3503                        + " pkg: " + packageName + ", info:" + info);
3504            }
3505            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3506        }
3507        if (DEBUG_EPHEMERAL) {
3508            Slog.v(TAG, "Ephemeral resolver NOT found");
3509        }
3510        return null;
3511    }
3512
3513    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3514        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3515        intent.addCategory(Intent.CATEGORY_DEFAULT);
3516        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3517
3518        final int resolveFlags =
3519                MATCH_DIRECT_BOOT_AWARE
3520                | MATCH_DIRECT_BOOT_UNAWARE
3521                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3522        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3523                resolveFlags, UserHandle.USER_SYSTEM);
3524        // temporarily look for the old action
3525        if (matches.isEmpty()) {
3526            if (DEBUG_EPHEMERAL) {
3527                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3528            }
3529            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3530            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3531                    resolveFlags, UserHandle.USER_SYSTEM);
3532        }
3533        Iterator<ResolveInfo> iter = matches.iterator();
3534        while (iter.hasNext()) {
3535            final ResolveInfo rInfo = iter.next();
3536            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3537            if (ps != null) {
3538                final PermissionsState permissionsState = ps.getPermissionsState();
3539                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3540                    continue;
3541                }
3542            }
3543            iter.remove();
3544        }
3545        if (matches.size() == 0) {
3546            return null;
3547        } else if (matches.size() == 1) {
3548            return (ActivityInfo) matches.get(0).getComponentInfo();
3549        } else {
3550            throw new RuntimeException(
3551                    "There must be at most one ephemeral installer; found " + matches);
3552        }
3553    }
3554
3555    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3556            @NonNull ComponentName resolver) {
3557        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3558                .addCategory(Intent.CATEGORY_DEFAULT)
3559                .setPackage(resolver.getPackageName());
3560        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3561        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3562                UserHandle.USER_SYSTEM);
3563        // temporarily look for the old action
3564        if (matches.isEmpty()) {
3565            if (DEBUG_EPHEMERAL) {
3566                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3567            }
3568            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3569            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3570                    UserHandle.USER_SYSTEM);
3571        }
3572        if (matches.isEmpty()) {
3573            return null;
3574        }
3575        return matches.get(0).getComponentInfo().getComponentName();
3576    }
3577
3578    private void primeDomainVerificationsLPw(int userId) {
3579        if (DEBUG_DOMAIN_VERIFICATION) {
3580            Slog.d(TAG, "Priming domain verifications in user " + userId);
3581        }
3582
3583        SystemConfig systemConfig = SystemConfig.getInstance();
3584        ArraySet<String> packages = systemConfig.getLinkedApps();
3585
3586        for (String packageName : packages) {
3587            PackageParser.Package pkg = mPackages.get(packageName);
3588            if (pkg != null) {
3589                if (!pkg.isSystemApp()) {
3590                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3591                    continue;
3592                }
3593
3594                ArraySet<String> domains = null;
3595                for (PackageParser.Activity a : pkg.activities) {
3596                    for (ActivityIntentInfo filter : a.intents) {
3597                        if (hasValidDomains(filter)) {
3598                            if (domains == null) {
3599                                domains = new ArraySet<String>();
3600                            }
3601                            domains.addAll(filter.getHostsList());
3602                        }
3603                    }
3604                }
3605
3606                if (domains != null && domains.size() > 0) {
3607                    if (DEBUG_DOMAIN_VERIFICATION) {
3608                        Slog.v(TAG, "      + " + packageName);
3609                    }
3610                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3611                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3612                    // and then 'always' in the per-user state actually used for intent resolution.
3613                    final IntentFilterVerificationInfo ivi;
3614                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3615                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3616                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3617                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3618                } else {
3619                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3620                            + "' does not handle web links");
3621                }
3622            } else {
3623                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3624            }
3625        }
3626
3627        scheduleWritePackageRestrictionsLocked(userId);
3628        scheduleWriteSettingsLocked();
3629    }
3630
3631    private void applyFactoryDefaultBrowserLPw(int userId) {
3632        // The default browser app's package name is stored in a string resource,
3633        // with a product-specific overlay used for vendor customization.
3634        String browserPkg = mContext.getResources().getString(
3635                com.android.internal.R.string.default_browser);
3636        if (!TextUtils.isEmpty(browserPkg)) {
3637            // non-empty string => required to be a known package
3638            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3639            if (ps == null) {
3640                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3641                browserPkg = null;
3642            } else {
3643                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3644            }
3645        }
3646
3647        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3648        // default.  If there's more than one, just leave everything alone.
3649        if (browserPkg == null) {
3650            calculateDefaultBrowserLPw(userId);
3651        }
3652    }
3653
3654    private void calculateDefaultBrowserLPw(int userId) {
3655        List<String> allBrowsers = resolveAllBrowserApps(userId);
3656        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3657        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3658    }
3659
3660    private List<String> resolveAllBrowserApps(int userId) {
3661        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3662        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3663                PackageManager.MATCH_ALL, userId);
3664
3665        final int count = list.size();
3666        List<String> result = new ArrayList<String>(count);
3667        for (int i=0; i<count; i++) {
3668            ResolveInfo info = list.get(i);
3669            if (info.activityInfo == null
3670                    || !info.handleAllWebDataURI
3671                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3672                    || result.contains(info.activityInfo.packageName)) {
3673                continue;
3674            }
3675            result.add(info.activityInfo.packageName);
3676        }
3677
3678        return result;
3679    }
3680
3681    private boolean packageIsBrowser(String packageName, int userId) {
3682        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3683                PackageManager.MATCH_ALL, userId);
3684        final int N = list.size();
3685        for (int i = 0; i < N; i++) {
3686            ResolveInfo info = list.get(i);
3687            if (packageName.equals(info.activityInfo.packageName)) {
3688                return true;
3689            }
3690        }
3691        return false;
3692    }
3693
3694    private void checkDefaultBrowser() {
3695        final int myUserId = UserHandle.myUserId();
3696        final String packageName = getDefaultBrowserPackageName(myUserId);
3697        if (packageName != null) {
3698            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3699            if (info == null) {
3700                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3701                synchronized (mPackages) {
3702                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3703                }
3704            }
3705        }
3706    }
3707
3708    @Override
3709    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3710            throws RemoteException {
3711        try {
3712            return super.onTransact(code, data, reply, flags);
3713        } catch (RuntimeException e) {
3714            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3715                Slog.wtf(TAG, "Package Manager Crash", e);
3716            }
3717            throw e;
3718        }
3719    }
3720
3721    static int[] appendInts(int[] cur, int[] add) {
3722        if (add == null) return cur;
3723        if (cur == null) return add;
3724        final int N = add.length;
3725        for (int i=0; i<N; i++) {
3726            cur = appendInt(cur, add[i]);
3727        }
3728        return cur;
3729    }
3730
3731    /**
3732     * Returns whether or not a full application can see an instant application.
3733     * <p>
3734     * Currently, there are three cases in which this can occur:
3735     * <ol>
3736     * <li>The calling application is a "special" process. The special
3737     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3738     *     and {@code 0}</li>
3739     * <li>The calling application has the permission
3740     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3741     * <li>The calling application is the default launcher on the
3742     *     system partition.</li>
3743     * </ol>
3744     */
3745    private boolean canViewInstantApps(int callingUid, int userId) {
3746        if (callingUid == Process.SYSTEM_UID
3747                || callingUid == Process.SHELL_UID
3748                || callingUid == Process.ROOT_UID) {
3749            return true;
3750        }
3751        if (mContext.checkCallingOrSelfPermission(
3752                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3753            return true;
3754        }
3755        if (mContext.checkCallingOrSelfPermission(
3756                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3757            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3758            if (homeComponent != null
3759                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3760                return true;
3761            }
3762        }
3763        return false;
3764    }
3765
3766    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3767        if (!sUserManager.exists(userId)) return null;
3768        if (ps == null) {
3769            return null;
3770        }
3771        PackageParser.Package p = ps.pkg;
3772        if (p == null) {
3773            return null;
3774        }
3775        final int callingUid = Binder.getCallingUid();
3776        // Filter out ephemeral app metadata:
3777        //   * The system/shell/root can see metadata for any app
3778        //   * An installed app can see metadata for 1) other installed apps
3779        //     and 2) ephemeral apps that have explicitly interacted with it
3780        //   * Ephemeral apps can only see their own data and exposed installed apps
3781        //   * Holding a signature permission allows seeing instant apps
3782        if (filterAppAccessLPr(ps, callingUid, userId)) {
3783            return null;
3784        }
3785
3786        final PermissionsState permissionsState = ps.getPermissionsState();
3787
3788        // Compute GIDs only if requested
3789        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3790                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3791        // Compute granted permissions only if package has requested permissions
3792        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3793                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3794        final PackageUserState state = ps.readUserState(userId);
3795
3796        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3797                && ps.isSystem()) {
3798            flags |= MATCH_ANY_USER;
3799        }
3800
3801        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3802                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3803
3804        if (packageInfo == null) {
3805            return null;
3806        }
3807
3808        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3809                resolveExternalPackageNameLPr(p);
3810
3811        return packageInfo;
3812    }
3813
3814    @Override
3815    public void checkPackageStartable(String packageName, int userId) {
3816        final int callingUid = Binder.getCallingUid();
3817        if (getInstantAppPackageName(callingUid) != null) {
3818            throw new SecurityException("Instant applications don't have access to this method");
3819        }
3820        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3821        synchronized (mPackages) {
3822            final PackageSetting ps = mSettings.mPackages.get(packageName);
3823            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3824                throw new SecurityException("Package " + packageName + " was not found!");
3825            }
3826
3827            if (!ps.getInstalled(userId)) {
3828                throw new SecurityException(
3829                        "Package " + packageName + " was not installed for user " + userId + "!");
3830            }
3831
3832            if (mSafeMode && !ps.isSystem()) {
3833                throw new SecurityException("Package " + packageName + " not a system app!");
3834            }
3835
3836            if (mFrozenPackages.contains(packageName)) {
3837                throw new SecurityException("Package " + packageName + " is currently frozen!");
3838            }
3839
3840            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3841                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3842                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3843            }
3844        }
3845    }
3846
3847    @Override
3848    public boolean isPackageAvailable(String packageName, int userId) {
3849        if (!sUserManager.exists(userId)) return false;
3850        final int callingUid = Binder.getCallingUid();
3851        enforceCrossUserPermission(callingUid, userId,
3852                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3853        synchronized (mPackages) {
3854            PackageParser.Package p = mPackages.get(packageName);
3855            if (p != null) {
3856                final PackageSetting ps = (PackageSetting) p.mExtras;
3857                if (filterAppAccessLPr(ps, callingUid, userId)) {
3858                    return false;
3859                }
3860                if (ps != null) {
3861                    final PackageUserState state = ps.readUserState(userId);
3862                    if (state != null) {
3863                        return PackageParser.isAvailable(state);
3864                    }
3865                }
3866            }
3867        }
3868        return false;
3869    }
3870
3871    @Override
3872    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3873        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3874                flags, Binder.getCallingUid(), userId);
3875    }
3876
3877    @Override
3878    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3879            int flags, int userId) {
3880        return getPackageInfoInternal(versionedPackage.getPackageName(),
3881                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3882    }
3883
3884    /**
3885     * Important: The provided filterCallingUid is used exclusively to filter out packages
3886     * that can be seen based on user state. It's typically the original caller uid prior
3887     * to clearing. Because it can only be provided by trusted code, it's value can be
3888     * trusted and will be used as-is; unlike userId which will be validated by this method.
3889     */
3890    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3891            int flags, int filterCallingUid, int userId) {
3892        if (!sUserManager.exists(userId)) return null;
3893        flags = updateFlagsForPackage(flags, userId, packageName);
3894        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3895                false /* requireFullPermission */, false /* checkShell */, "get package info");
3896
3897        // reader
3898        synchronized (mPackages) {
3899            // Normalize package name to handle renamed packages and static libs
3900            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3901
3902            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3903            if (matchFactoryOnly) {
3904                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3905                if (ps != null) {
3906                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3907                        return null;
3908                    }
3909                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3910                        return null;
3911                    }
3912                    return generatePackageInfo(ps, flags, userId);
3913                }
3914            }
3915
3916            PackageParser.Package p = mPackages.get(packageName);
3917            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3918                return null;
3919            }
3920            if (DEBUG_PACKAGE_INFO)
3921                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3922            if (p != null) {
3923                final PackageSetting ps = (PackageSetting) p.mExtras;
3924                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3925                    return null;
3926                }
3927                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3928                    return null;
3929                }
3930                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3931            }
3932            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3933                final PackageSetting ps = mSettings.mPackages.get(packageName);
3934                if (ps == null) return null;
3935                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3936                    return null;
3937                }
3938                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3939                    return null;
3940                }
3941                return generatePackageInfo(ps, flags, userId);
3942            }
3943        }
3944        return null;
3945    }
3946
3947    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3948        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3949            return true;
3950        }
3951        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3952            return true;
3953        }
3954        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3955            return true;
3956        }
3957        return false;
3958    }
3959
3960    private boolean isComponentVisibleToInstantApp(
3961            @Nullable ComponentName component, @ComponentType int type) {
3962        if (type == TYPE_ACTIVITY) {
3963            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3964            return activity != null
3965                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3966                    : false;
3967        } else if (type == TYPE_RECEIVER) {
3968            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3969            return activity != null
3970                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3971                    : false;
3972        } else if (type == TYPE_SERVICE) {
3973            final PackageParser.Service service = mServices.mServices.get(component);
3974            return service != null
3975                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3976                    : false;
3977        } else if (type == TYPE_PROVIDER) {
3978            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3979            return provider != null
3980                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3981                    : false;
3982        } else if (type == TYPE_UNKNOWN) {
3983            return isComponentVisibleToInstantApp(component);
3984        }
3985        return false;
3986    }
3987
3988    /**
3989     * Returns whether or not access to the application should be filtered.
3990     * <p>
3991     * Access may be limited based upon whether the calling or target applications
3992     * are instant applications.
3993     *
3994     * @see #canAccessInstantApps(int)
3995     */
3996    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3997            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3998        // if we're in an isolated process, get the real calling UID
3999        if (Process.isIsolated(callingUid)) {
4000            callingUid = mIsolatedOwners.get(callingUid);
4001        }
4002        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4003        final boolean callerIsInstantApp = instantAppPkgName != null;
4004        if (ps == null) {
4005            if (callerIsInstantApp) {
4006                // pretend the application exists, but, needs to be filtered
4007                return true;
4008            }
4009            return false;
4010        }
4011        // if the target and caller are the same application, don't filter
4012        if (isCallerSameApp(ps.name, callingUid)) {
4013            return false;
4014        }
4015        if (callerIsInstantApp) {
4016            // request for a specific component; if it hasn't been explicitly exposed, filter
4017            if (component != null) {
4018                return !isComponentVisibleToInstantApp(component, componentType);
4019            }
4020            // request for application; if no components have been explicitly exposed, filter
4021            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4022        }
4023        if (ps.getInstantApp(userId)) {
4024            // caller can see all components of all instant applications, don't filter
4025            if (canViewInstantApps(callingUid, userId)) {
4026                return false;
4027            }
4028            // request for a specific instant application component, filter
4029            if (component != null) {
4030                return true;
4031            }
4032            // request for an instant application; if the caller hasn't been granted access, filter
4033            return !mInstantAppRegistry.isInstantAccessGranted(
4034                    userId, UserHandle.getAppId(callingUid), ps.appId);
4035        }
4036        return false;
4037    }
4038
4039    /**
4040     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4041     */
4042    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4043        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4044    }
4045
4046    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4047            int flags) {
4048        // Callers can access only the libs they depend on, otherwise they need to explicitly
4049        // ask for the shared libraries given the caller is allowed to access all static libs.
4050        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4051            // System/shell/root get to see all static libs
4052            final int appId = UserHandle.getAppId(uid);
4053            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4054                    || appId == Process.ROOT_UID) {
4055                return false;
4056            }
4057        }
4058
4059        // No package means no static lib as it is always on internal storage
4060        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4061            return false;
4062        }
4063
4064        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4065                ps.pkg.staticSharedLibVersion);
4066        if (libEntry == null) {
4067            return false;
4068        }
4069
4070        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4071        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4072        if (uidPackageNames == null) {
4073            return true;
4074        }
4075
4076        for (String uidPackageName : uidPackageNames) {
4077            if (ps.name.equals(uidPackageName)) {
4078                return false;
4079            }
4080            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4081            if (uidPs != null) {
4082                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4083                        libEntry.info.getName());
4084                if (index < 0) {
4085                    continue;
4086                }
4087                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4088                    return false;
4089                }
4090            }
4091        }
4092        return true;
4093    }
4094
4095    @Override
4096    public String[] currentToCanonicalPackageNames(String[] names) {
4097        final int callingUid = Binder.getCallingUid();
4098        if (getInstantAppPackageName(callingUid) != null) {
4099            return names;
4100        }
4101        final String[] out = new String[names.length];
4102        // reader
4103        synchronized (mPackages) {
4104            final int callingUserId = UserHandle.getUserId(callingUid);
4105            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4106            for (int i=names.length-1; i>=0; i--) {
4107                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4108                boolean translateName = false;
4109                if (ps != null && ps.realName != null) {
4110                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4111                    translateName = !targetIsInstantApp
4112                            || canViewInstantApps
4113                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4114                                    UserHandle.getAppId(callingUid), ps.appId);
4115                }
4116                out[i] = translateName ? ps.realName : names[i];
4117            }
4118        }
4119        return out;
4120    }
4121
4122    @Override
4123    public String[] canonicalToCurrentPackageNames(String[] names) {
4124        final int callingUid = Binder.getCallingUid();
4125        if (getInstantAppPackageName(callingUid) != null) {
4126            return names;
4127        }
4128        final String[] out = new String[names.length];
4129        // reader
4130        synchronized (mPackages) {
4131            final int callingUserId = UserHandle.getUserId(callingUid);
4132            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4133            for (int i=names.length-1; i>=0; i--) {
4134                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4135                boolean translateName = false;
4136                if (cur != null) {
4137                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4138                    final boolean targetIsInstantApp =
4139                            ps != null && ps.getInstantApp(callingUserId);
4140                    translateName = !targetIsInstantApp
4141                            || canViewInstantApps
4142                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4143                                    UserHandle.getAppId(callingUid), ps.appId);
4144                }
4145                out[i] = translateName ? cur : names[i];
4146            }
4147        }
4148        return out;
4149    }
4150
4151    @Override
4152    public int getPackageUid(String packageName, int flags, int userId) {
4153        if (!sUserManager.exists(userId)) return -1;
4154        final int callingUid = Binder.getCallingUid();
4155        flags = updateFlagsForPackage(flags, userId, packageName);
4156        enforceCrossUserPermission(callingUid, userId,
4157                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4158
4159        // reader
4160        synchronized (mPackages) {
4161            final PackageParser.Package p = mPackages.get(packageName);
4162            if (p != null && p.isMatch(flags)) {
4163                PackageSetting ps = (PackageSetting) p.mExtras;
4164                if (filterAppAccessLPr(ps, callingUid, userId)) {
4165                    return -1;
4166                }
4167                return UserHandle.getUid(userId, p.applicationInfo.uid);
4168            }
4169            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4170                final PackageSetting ps = mSettings.mPackages.get(packageName);
4171                if (ps != null && ps.isMatch(flags)
4172                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4173                    return UserHandle.getUid(userId, ps.appId);
4174                }
4175            }
4176        }
4177
4178        return -1;
4179    }
4180
4181    @Override
4182    public int[] getPackageGids(String packageName, int flags, int userId) {
4183        if (!sUserManager.exists(userId)) return null;
4184        final int callingUid = Binder.getCallingUid();
4185        flags = updateFlagsForPackage(flags, userId, packageName);
4186        enforceCrossUserPermission(callingUid, userId,
4187                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4188
4189        // reader
4190        synchronized (mPackages) {
4191            final PackageParser.Package p = mPackages.get(packageName);
4192            if (p != null && p.isMatch(flags)) {
4193                PackageSetting ps = (PackageSetting) p.mExtras;
4194                if (filterAppAccessLPr(ps, callingUid, userId)) {
4195                    return null;
4196                }
4197                // TODO: Shouldn't this be checking for package installed state for userId and
4198                // return null?
4199                return ps.getPermissionsState().computeGids(userId);
4200            }
4201            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4202                final PackageSetting ps = mSettings.mPackages.get(packageName);
4203                if (ps != null && ps.isMatch(flags)
4204                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4205                    return ps.getPermissionsState().computeGids(userId);
4206                }
4207            }
4208        }
4209
4210        return null;
4211    }
4212
4213    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4214        if (bp.perm != null) {
4215            return PackageParser.generatePermissionInfo(bp.perm, flags);
4216        }
4217        PermissionInfo pi = new PermissionInfo();
4218        pi.name = bp.name;
4219        pi.packageName = bp.sourcePackage;
4220        pi.nonLocalizedLabel = bp.name;
4221        pi.protectionLevel = bp.protectionLevel;
4222        return pi;
4223    }
4224
4225    @Override
4226    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4227        final int callingUid = Binder.getCallingUid();
4228        if (getInstantAppPackageName(callingUid) != null) {
4229            return null;
4230        }
4231        // reader
4232        synchronized (mPackages) {
4233            final BasePermission p = mSettings.mPermissions.get(name);
4234            if (p == null) {
4235                return null;
4236            }
4237            // If the caller is an app that targets pre 26 SDK drop protection flags.
4238            final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4239            if (permissionInfo != null) {
4240                permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4241                        permissionInfo.protectionLevel, packageName, callingUid);
4242            }
4243            return permissionInfo;
4244        }
4245    }
4246
4247    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4248            String packageName, int uid) {
4249        // Signature permission flags area always reported
4250        final int protectionLevelMasked = protectionLevel
4251                & (PermissionInfo.PROTECTION_NORMAL
4252                | PermissionInfo.PROTECTION_DANGEROUS
4253                | PermissionInfo.PROTECTION_SIGNATURE);
4254        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4255            return protectionLevel;
4256        }
4257
4258        // System sees all flags.
4259        final int appId = UserHandle.getAppId(uid);
4260        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4261                || appId == Process.SHELL_UID) {
4262            return protectionLevel;
4263        }
4264
4265        // Normalize package name to handle renamed packages and static libs
4266        packageName = resolveInternalPackageNameLPr(packageName,
4267                PackageManager.VERSION_CODE_HIGHEST);
4268
4269        // Apps that target O see flags for all protection levels.
4270        final PackageSetting ps = mSettings.mPackages.get(packageName);
4271        if (ps == null) {
4272            return protectionLevel;
4273        }
4274        if (ps.appId != appId) {
4275            return protectionLevel;
4276        }
4277
4278        final PackageParser.Package pkg = mPackages.get(packageName);
4279        if (pkg == null) {
4280            return protectionLevel;
4281        }
4282        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4283            return protectionLevelMasked;
4284        }
4285
4286        return protectionLevel;
4287    }
4288
4289    @Override
4290    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4291            int flags) {
4292        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4293            return null;
4294        }
4295        // reader
4296        synchronized (mPackages) {
4297            if (group != null && !mPermissionGroups.containsKey(group)) {
4298                // This is thrown as NameNotFoundException
4299                return null;
4300            }
4301
4302            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4303            for (BasePermission p : mSettings.mPermissions.values()) {
4304                if (group == null) {
4305                    if (p.perm == null || p.perm.info.group == null) {
4306                        out.add(generatePermissionInfo(p, flags));
4307                    }
4308                } else {
4309                    if (p.perm != null && group.equals(p.perm.info.group)) {
4310                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4311                    }
4312                }
4313            }
4314            return new ParceledListSlice<>(out);
4315        }
4316    }
4317
4318    @Override
4319    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4320        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4321            return null;
4322        }
4323        // reader
4324        synchronized (mPackages) {
4325            return PackageParser.generatePermissionGroupInfo(
4326                    mPermissionGroups.get(name), flags);
4327        }
4328    }
4329
4330    @Override
4331    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4332        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4333            return ParceledListSlice.emptyList();
4334        }
4335        // reader
4336        synchronized (mPackages) {
4337            final int N = mPermissionGroups.size();
4338            ArrayList<PermissionGroupInfo> out
4339                    = new ArrayList<PermissionGroupInfo>(N);
4340            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4341                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4342            }
4343            return new ParceledListSlice<>(out);
4344        }
4345    }
4346
4347    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4348            int filterCallingUid, int userId) {
4349        if (!sUserManager.exists(userId)) return null;
4350        PackageSetting ps = mSettings.mPackages.get(packageName);
4351        if (ps != null) {
4352            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4353                return null;
4354            }
4355            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4356                return null;
4357            }
4358            if (ps.pkg == null) {
4359                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4360                if (pInfo != null) {
4361                    return pInfo.applicationInfo;
4362                }
4363                return null;
4364            }
4365            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4366                    ps.readUserState(userId), userId);
4367            if (ai != null) {
4368                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4369            }
4370            return ai;
4371        }
4372        return null;
4373    }
4374
4375    @Override
4376    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4377        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4378    }
4379
4380    /**
4381     * Important: The provided filterCallingUid is used exclusively to filter out applications
4382     * that can be seen based on user state. It's typically the original caller uid prior
4383     * to clearing. Because it can only be provided by trusted code, it's value can be
4384     * trusted and will be used as-is; unlike userId which will be validated by this method.
4385     */
4386    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4387            int filterCallingUid, int userId) {
4388        if (!sUserManager.exists(userId)) return null;
4389        flags = updateFlagsForApplication(flags, userId, packageName);
4390        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4391                false /* requireFullPermission */, false /* checkShell */, "get application info");
4392
4393        // writer
4394        synchronized (mPackages) {
4395            // Normalize package name to handle renamed packages and static libs
4396            packageName = resolveInternalPackageNameLPr(packageName,
4397                    PackageManager.VERSION_CODE_HIGHEST);
4398
4399            PackageParser.Package p = mPackages.get(packageName);
4400            if (DEBUG_PACKAGE_INFO) Log.v(
4401                    TAG, "getApplicationInfo " + packageName
4402                    + ": " + p);
4403            if (p != null) {
4404                PackageSetting ps = mSettings.mPackages.get(packageName);
4405                if (ps == null) return null;
4406                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4407                    return null;
4408                }
4409                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4410                    return null;
4411                }
4412                // Note: isEnabledLP() does not apply here - always return info
4413                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4414                        p, flags, ps.readUserState(userId), userId);
4415                if (ai != null) {
4416                    ai.packageName = resolveExternalPackageNameLPr(p);
4417                }
4418                return ai;
4419            }
4420            if ("android".equals(packageName)||"system".equals(packageName)) {
4421                return mAndroidApplication;
4422            }
4423            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4424                // Already generates the external package name
4425                return generateApplicationInfoFromSettingsLPw(packageName,
4426                        flags, filterCallingUid, userId);
4427            }
4428        }
4429        return null;
4430    }
4431
4432    private String normalizePackageNameLPr(String packageName) {
4433        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4434        return normalizedPackageName != null ? normalizedPackageName : packageName;
4435    }
4436
4437    @Override
4438    public void deletePreloadsFileCache() {
4439        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4440            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4441        }
4442        File dir = Environment.getDataPreloadsFileCacheDirectory();
4443        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4444        FileUtils.deleteContents(dir);
4445    }
4446
4447    @Override
4448    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4449            final int storageFlags, final IPackageDataObserver observer) {
4450        mContext.enforceCallingOrSelfPermission(
4451                android.Manifest.permission.CLEAR_APP_CACHE, null);
4452        mHandler.post(() -> {
4453            boolean success = false;
4454            try {
4455                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4456                success = true;
4457            } catch (IOException e) {
4458                Slog.w(TAG, e);
4459            }
4460            if (observer != null) {
4461                try {
4462                    observer.onRemoveCompleted(null, success);
4463                } catch (RemoteException e) {
4464                    Slog.w(TAG, e);
4465                }
4466            }
4467        });
4468    }
4469
4470    @Override
4471    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4472            final int storageFlags, final IntentSender pi) {
4473        mContext.enforceCallingOrSelfPermission(
4474                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4475        mHandler.post(() -> {
4476            boolean success = false;
4477            try {
4478                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4479                success = true;
4480            } catch (IOException e) {
4481                Slog.w(TAG, e);
4482            }
4483            if (pi != null) {
4484                try {
4485                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4486                } catch (SendIntentException e) {
4487                    Slog.w(TAG, e);
4488                }
4489            }
4490        });
4491    }
4492
4493    /**
4494     * Blocking call to clear various types of cached data across the system
4495     * until the requested bytes are available.
4496     */
4497    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4498        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4499        final File file = storage.findPathForUuid(volumeUuid);
4500        if (file.getUsableSpace() >= bytes) return;
4501
4502        if (ENABLE_FREE_CACHE_V2) {
4503            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4504                    volumeUuid);
4505            final boolean aggressive = (storageFlags
4506                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4507            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4508
4509            // 1. Pre-flight to determine if we have any chance to succeed
4510            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4511            if (internalVolume && (aggressive || SystemProperties
4512                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4513                deletePreloadsFileCache();
4514                if (file.getUsableSpace() >= bytes) return;
4515            }
4516
4517            // 3. Consider parsed APK data (aggressive only)
4518            if (internalVolume && aggressive) {
4519                FileUtils.deleteContents(mCacheDir);
4520                if (file.getUsableSpace() >= bytes) return;
4521            }
4522
4523            // 4. Consider cached app data (above quotas)
4524            try {
4525                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4526                        Installer.FLAG_FREE_CACHE_V2);
4527            } catch (InstallerException ignored) {
4528            }
4529            if (file.getUsableSpace() >= bytes) return;
4530
4531            // 5. Consider shared libraries with refcount=0 and age>min cache period
4532            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4533                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4534                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4535                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4536                return;
4537            }
4538
4539            // 6. Consider dexopt output (aggressive only)
4540            // TODO: Implement
4541
4542            // 7. Consider installed instant apps unused longer than min cache period
4543            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4544                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4545                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4546                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4547                return;
4548            }
4549
4550            // 8. Consider cached app data (below quotas)
4551            try {
4552                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4553                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4554            } catch (InstallerException ignored) {
4555            }
4556            if (file.getUsableSpace() >= bytes) return;
4557
4558            // 9. Consider DropBox entries
4559            // TODO: Implement
4560
4561            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4562            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4563                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4564                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4565                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4566                return;
4567            }
4568        } else {
4569            try {
4570                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4571            } catch (InstallerException ignored) {
4572            }
4573            if (file.getUsableSpace() >= bytes) return;
4574        }
4575
4576        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4577    }
4578
4579    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4580            throws IOException {
4581        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4582        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4583
4584        List<VersionedPackage> packagesToDelete = null;
4585        final long now = System.currentTimeMillis();
4586
4587        synchronized (mPackages) {
4588            final int[] allUsers = sUserManager.getUserIds();
4589            final int libCount = mSharedLibraries.size();
4590            for (int i = 0; i < libCount; i++) {
4591                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4592                if (versionedLib == null) {
4593                    continue;
4594                }
4595                final int versionCount = versionedLib.size();
4596                for (int j = 0; j < versionCount; j++) {
4597                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4598                    // Skip packages that are not static shared libs.
4599                    if (!libInfo.isStatic()) {
4600                        break;
4601                    }
4602                    // Important: We skip static shared libs used for some user since
4603                    // in such a case we need to keep the APK on the device. The check for
4604                    // a lib being used for any user is performed by the uninstall call.
4605                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4606                    // Resolve the package name - we use synthetic package names internally
4607                    final String internalPackageName = resolveInternalPackageNameLPr(
4608                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4609                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4610                    // Skip unused static shared libs cached less than the min period
4611                    // to prevent pruning a lib needed by a subsequently installed package.
4612                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4613                        continue;
4614                    }
4615                    if (packagesToDelete == null) {
4616                        packagesToDelete = new ArrayList<>();
4617                    }
4618                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4619                            declaringPackage.getVersionCode()));
4620                }
4621            }
4622        }
4623
4624        if (packagesToDelete != null) {
4625            final int packageCount = packagesToDelete.size();
4626            for (int i = 0; i < packageCount; i++) {
4627                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4628                // Delete the package synchronously (will fail of the lib used for any user).
4629                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4630                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4631                                == PackageManager.DELETE_SUCCEEDED) {
4632                    if (volume.getUsableSpace() >= neededSpace) {
4633                        return true;
4634                    }
4635                }
4636            }
4637        }
4638
4639        return false;
4640    }
4641
4642    /**
4643     * Update given flags based on encryption status of current user.
4644     */
4645    private int updateFlags(int flags, int userId) {
4646        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4647                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4648            // Caller expressed an explicit opinion about what encryption
4649            // aware/unaware components they want to see, so fall through and
4650            // give them what they want
4651        } else {
4652            // Caller expressed no opinion, so match based on user state
4653            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4654                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4655            } else {
4656                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4657            }
4658        }
4659        return flags;
4660    }
4661
4662    private UserManagerInternal getUserManagerInternal() {
4663        if (mUserManagerInternal == null) {
4664            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4665        }
4666        return mUserManagerInternal;
4667    }
4668
4669    private DeviceIdleController.LocalService getDeviceIdleController() {
4670        if (mDeviceIdleController == null) {
4671            mDeviceIdleController =
4672                    LocalServices.getService(DeviceIdleController.LocalService.class);
4673        }
4674        return mDeviceIdleController;
4675    }
4676
4677    /**
4678     * Update given flags when being used to request {@link PackageInfo}.
4679     */
4680    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4681        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4682        boolean triaged = true;
4683        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4684                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4685            // Caller is asking for component details, so they'd better be
4686            // asking for specific encryption matching behavior, or be triaged
4687            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4688                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4689                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4690                triaged = false;
4691            }
4692        }
4693        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4694                | PackageManager.MATCH_SYSTEM_ONLY
4695                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4696            triaged = false;
4697        }
4698        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4699            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4700                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4701                    + Debug.getCallers(5));
4702        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4703                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4704            // If the caller wants all packages and has a restricted profile associated with it,
4705            // then match all users. This is to make sure that launchers that need to access work
4706            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4707            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4708            flags |= PackageManager.MATCH_ANY_USER;
4709        }
4710        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4711            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4712                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4713        }
4714        return updateFlags(flags, userId);
4715    }
4716
4717    /**
4718     * Update given flags when being used to request {@link ApplicationInfo}.
4719     */
4720    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4721        return updateFlagsForPackage(flags, userId, cookie);
4722    }
4723
4724    /**
4725     * Update given flags when being used to request {@link ComponentInfo}.
4726     */
4727    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4728        if (cookie instanceof Intent) {
4729            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4730                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4731            }
4732        }
4733
4734        boolean triaged = true;
4735        // Caller is asking for component details, so they'd better be
4736        // asking for specific encryption matching behavior, or be triaged
4737        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4738                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4739                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4740            triaged = false;
4741        }
4742        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4743            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4744                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4745        }
4746
4747        return updateFlags(flags, userId);
4748    }
4749
4750    /**
4751     * Update given intent when being used to request {@link ResolveInfo}.
4752     */
4753    private Intent updateIntentForResolve(Intent intent) {
4754        if (intent.getSelector() != null) {
4755            intent = intent.getSelector();
4756        }
4757        if (DEBUG_PREFERRED) {
4758            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4759        }
4760        return intent;
4761    }
4762
4763    /**
4764     * Update given flags when being used to request {@link ResolveInfo}.
4765     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4766     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4767     * flag set. However, this flag is only honoured in three circumstances:
4768     * <ul>
4769     * <li>when called from a system process</li>
4770     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4771     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4772     * action and a {@code android.intent.category.BROWSABLE} category</li>
4773     * </ul>
4774     */
4775    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4776        return updateFlagsForResolve(flags, userId, intent, callingUid,
4777                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4778    }
4779    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4780            boolean wantInstantApps) {
4781        return updateFlagsForResolve(flags, userId, intent, callingUid,
4782                wantInstantApps, false /*onlyExposedExplicitly*/);
4783    }
4784    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4785            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4786        // Safe mode means we shouldn't match any third-party components
4787        if (mSafeMode) {
4788            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4789        }
4790        if (getInstantAppPackageName(callingUid) != null) {
4791            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4792            if (onlyExposedExplicitly) {
4793                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4794            }
4795            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4796            flags |= PackageManager.MATCH_INSTANT;
4797        } else {
4798            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4799            final boolean allowMatchInstant =
4800                    (wantInstantApps
4801                            && Intent.ACTION_VIEW.equals(intent.getAction())
4802                            && hasWebURI(intent))
4803                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4804            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4805                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4806            if (!allowMatchInstant) {
4807                flags &= ~PackageManager.MATCH_INSTANT;
4808            }
4809        }
4810        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4811    }
4812
4813    @Override
4814    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4815        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4816    }
4817
4818    /**
4819     * Important: The provided filterCallingUid is used exclusively to filter out activities
4820     * that can be seen based on user state. It's typically the original caller uid prior
4821     * to clearing. Because it can only be provided by trusted code, it's value can be
4822     * trusted and will be used as-is; unlike userId which will be validated by this method.
4823     */
4824    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4825            int filterCallingUid, int userId) {
4826        if (!sUserManager.exists(userId)) return null;
4827        flags = updateFlagsForComponent(flags, userId, component);
4828        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4829                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4830        synchronized (mPackages) {
4831            PackageParser.Activity a = mActivities.mActivities.get(component);
4832
4833            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4834            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4835                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4836                if (ps == null) return null;
4837                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4838                    return null;
4839                }
4840                return PackageParser.generateActivityInfo(
4841                        a, flags, ps.readUserState(userId), userId);
4842            }
4843            if (mResolveComponentName.equals(component)) {
4844                return PackageParser.generateActivityInfo(
4845                        mResolveActivity, flags, new PackageUserState(), userId);
4846            }
4847        }
4848        return null;
4849    }
4850
4851    @Override
4852    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4853            String resolvedType) {
4854        synchronized (mPackages) {
4855            if (component.equals(mResolveComponentName)) {
4856                // The resolver supports EVERYTHING!
4857                return true;
4858            }
4859            final int callingUid = Binder.getCallingUid();
4860            final int callingUserId = UserHandle.getUserId(callingUid);
4861            PackageParser.Activity a = mActivities.mActivities.get(component);
4862            if (a == null) {
4863                return false;
4864            }
4865            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4866            if (ps == null) {
4867                return false;
4868            }
4869            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4870                return false;
4871            }
4872            for (int i=0; i<a.intents.size(); i++) {
4873                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4874                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4875                    return true;
4876                }
4877            }
4878            return false;
4879        }
4880    }
4881
4882    @Override
4883    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4884        if (!sUserManager.exists(userId)) return null;
4885        final int callingUid = Binder.getCallingUid();
4886        flags = updateFlagsForComponent(flags, userId, component);
4887        enforceCrossUserPermission(callingUid, userId,
4888                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4889        synchronized (mPackages) {
4890            PackageParser.Activity a = mReceivers.mActivities.get(component);
4891            if (DEBUG_PACKAGE_INFO) Log.v(
4892                TAG, "getReceiverInfo " + component + ": " + a);
4893            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4894                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4895                if (ps == null) return null;
4896                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4897                    return null;
4898                }
4899                return PackageParser.generateActivityInfo(
4900                        a, flags, ps.readUserState(userId), userId);
4901            }
4902        }
4903        return null;
4904    }
4905
4906    @Override
4907    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4908            int flags, int userId) {
4909        if (!sUserManager.exists(userId)) return null;
4910        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4911        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4912            return null;
4913        }
4914
4915        flags = updateFlagsForPackage(flags, userId, null);
4916
4917        final boolean canSeeStaticLibraries =
4918                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4919                        == PERMISSION_GRANTED
4920                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4921                        == PERMISSION_GRANTED
4922                || canRequestPackageInstallsInternal(packageName,
4923                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4924                        false  /* throwIfPermNotDeclared*/)
4925                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4926                        == PERMISSION_GRANTED;
4927
4928        synchronized (mPackages) {
4929            List<SharedLibraryInfo> result = null;
4930
4931            final int libCount = mSharedLibraries.size();
4932            for (int i = 0; i < libCount; i++) {
4933                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4934                if (versionedLib == null) {
4935                    continue;
4936                }
4937
4938                final int versionCount = versionedLib.size();
4939                for (int j = 0; j < versionCount; j++) {
4940                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4941                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4942                        break;
4943                    }
4944                    final long identity = Binder.clearCallingIdentity();
4945                    try {
4946                        PackageInfo packageInfo = getPackageInfoVersioned(
4947                                libInfo.getDeclaringPackage(), flags
4948                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4949                        if (packageInfo == null) {
4950                            continue;
4951                        }
4952                    } finally {
4953                        Binder.restoreCallingIdentity(identity);
4954                    }
4955
4956                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4957                            libInfo.getVersion(), libInfo.getType(),
4958                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4959                            flags, userId));
4960
4961                    if (result == null) {
4962                        result = new ArrayList<>();
4963                    }
4964                    result.add(resLibInfo);
4965                }
4966            }
4967
4968            return result != null ? new ParceledListSlice<>(result) : null;
4969        }
4970    }
4971
4972    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4973            SharedLibraryInfo libInfo, int flags, int userId) {
4974        List<VersionedPackage> versionedPackages = null;
4975        final int packageCount = mSettings.mPackages.size();
4976        for (int i = 0; i < packageCount; i++) {
4977            PackageSetting ps = mSettings.mPackages.valueAt(i);
4978
4979            if (ps == null) {
4980                continue;
4981            }
4982
4983            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4984                continue;
4985            }
4986
4987            final String libName = libInfo.getName();
4988            if (libInfo.isStatic()) {
4989                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4990                if (libIdx < 0) {
4991                    continue;
4992                }
4993                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4994                    continue;
4995                }
4996                if (versionedPackages == null) {
4997                    versionedPackages = new ArrayList<>();
4998                }
4999                // If the dependent is a static shared lib, use the public package name
5000                String dependentPackageName = ps.name;
5001                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5002                    dependentPackageName = ps.pkg.manifestPackageName;
5003                }
5004                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5005            } else if (ps.pkg != null) {
5006                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5007                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5008                    if (versionedPackages == null) {
5009                        versionedPackages = new ArrayList<>();
5010                    }
5011                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5012                }
5013            }
5014        }
5015
5016        return versionedPackages;
5017    }
5018
5019    @Override
5020    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5021        if (!sUserManager.exists(userId)) return null;
5022        final int callingUid = Binder.getCallingUid();
5023        flags = updateFlagsForComponent(flags, userId, component);
5024        enforceCrossUserPermission(callingUid, userId,
5025                false /* requireFullPermission */, false /* checkShell */, "get service info");
5026        synchronized (mPackages) {
5027            PackageParser.Service s = mServices.mServices.get(component);
5028            if (DEBUG_PACKAGE_INFO) Log.v(
5029                TAG, "getServiceInfo " + component + ": " + s);
5030            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5031                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5032                if (ps == null) return null;
5033                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5034                    return null;
5035                }
5036                return PackageParser.generateServiceInfo(
5037                        s, flags, ps.readUserState(userId), userId);
5038            }
5039        }
5040        return null;
5041    }
5042
5043    @Override
5044    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5045        if (!sUserManager.exists(userId)) return null;
5046        final int callingUid = Binder.getCallingUid();
5047        flags = updateFlagsForComponent(flags, userId, component);
5048        enforceCrossUserPermission(callingUid, userId,
5049                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5050        synchronized (mPackages) {
5051            PackageParser.Provider p = mProviders.mProviders.get(component);
5052            if (DEBUG_PACKAGE_INFO) Log.v(
5053                TAG, "getProviderInfo " + component + ": " + p);
5054            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5055                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5056                if (ps == null) return null;
5057                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5058                    return null;
5059                }
5060                return PackageParser.generateProviderInfo(
5061                        p, flags, ps.readUserState(userId), userId);
5062            }
5063        }
5064        return null;
5065    }
5066
5067    @Override
5068    public String[] getSystemSharedLibraryNames() {
5069        // allow instant applications
5070        synchronized (mPackages) {
5071            Set<String> libs = null;
5072            final int libCount = mSharedLibraries.size();
5073            for (int i = 0; i < libCount; i++) {
5074                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5075                if (versionedLib == null) {
5076                    continue;
5077                }
5078                final int versionCount = versionedLib.size();
5079                for (int j = 0; j < versionCount; j++) {
5080                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5081                    if (!libEntry.info.isStatic()) {
5082                        if (libs == null) {
5083                            libs = new ArraySet<>();
5084                        }
5085                        libs.add(libEntry.info.getName());
5086                        break;
5087                    }
5088                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5089                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5090                            UserHandle.getUserId(Binder.getCallingUid()),
5091                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5092                        if (libs == null) {
5093                            libs = new ArraySet<>();
5094                        }
5095                        libs.add(libEntry.info.getName());
5096                        break;
5097                    }
5098                }
5099            }
5100
5101            if (libs != null) {
5102                String[] libsArray = new String[libs.size()];
5103                libs.toArray(libsArray);
5104                return libsArray;
5105            }
5106
5107            return null;
5108        }
5109    }
5110
5111    @Override
5112    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5113        // allow instant applications
5114        synchronized (mPackages) {
5115            return mServicesSystemSharedLibraryPackageName;
5116        }
5117    }
5118
5119    @Override
5120    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5121        // allow instant applications
5122        synchronized (mPackages) {
5123            return mSharedSystemSharedLibraryPackageName;
5124        }
5125    }
5126
5127    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5128        for (int i = userList.length - 1; i >= 0; --i) {
5129            final int userId = userList[i];
5130            // don't add instant app to the list of updates
5131            if (pkgSetting.getInstantApp(userId)) {
5132                continue;
5133            }
5134            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5135            if (changedPackages == null) {
5136                changedPackages = new SparseArray<>();
5137                mChangedPackages.put(userId, changedPackages);
5138            }
5139            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5140            if (sequenceNumbers == null) {
5141                sequenceNumbers = new HashMap<>();
5142                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5143            }
5144            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5145            if (sequenceNumber != null) {
5146                changedPackages.remove(sequenceNumber);
5147            }
5148            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5149            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5150        }
5151        mChangedPackagesSequenceNumber++;
5152    }
5153
5154    @Override
5155    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5156        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5157            return null;
5158        }
5159        synchronized (mPackages) {
5160            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5161                return null;
5162            }
5163            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5164            if (changedPackages == null) {
5165                return null;
5166            }
5167            final List<String> packageNames =
5168                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5169            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5170                final String packageName = changedPackages.get(i);
5171                if (packageName != null) {
5172                    packageNames.add(packageName);
5173                }
5174            }
5175            return packageNames.isEmpty()
5176                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5177        }
5178    }
5179
5180    @Override
5181    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5182        // allow instant applications
5183        ArrayList<FeatureInfo> res;
5184        synchronized (mAvailableFeatures) {
5185            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5186            res.addAll(mAvailableFeatures.values());
5187        }
5188        final FeatureInfo fi = new FeatureInfo();
5189        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5190                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5191        res.add(fi);
5192
5193        return new ParceledListSlice<>(res);
5194    }
5195
5196    @Override
5197    public boolean hasSystemFeature(String name, int version) {
5198        // allow instant applications
5199        synchronized (mAvailableFeatures) {
5200            final FeatureInfo feat = mAvailableFeatures.get(name);
5201            if (feat == null) {
5202                return false;
5203            } else {
5204                return feat.version >= version;
5205            }
5206        }
5207    }
5208
5209    @Override
5210    public int checkPermission(String permName, String pkgName, int userId) {
5211        if (!sUserManager.exists(userId)) {
5212            return PackageManager.PERMISSION_DENIED;
5213        }
5214        final int callingUid = Binder.getCallingUid();
5215
5216        synchronized (mPackages) {
5217            final PackageParser.Package p = mPackages.get(pkgName);
5218            if (p != null && p.mExtras != null) {
5219                final PackageSetting ps = (PackageSetting) p.mExtras;
5220                if (filterAppAccessLPr(ps, callingUid, userId)) {
5221                    return PackageManager.PERMISSION_DENIED;
5222                }
5223                final boolean instantApp = ps.getInstantApp(userId);
5224                final PermissionsState permissionsState = ps.getPermissionsState();
5225                if (permissionsState.hasPermission(permName, userId)) {
5226                    if (instantApp) {
5227                        BasePermission bp = mSettings.mPermissions.get(permName);
5228                        if (bp != null && bp.isInstant()) {
5229                            return PackageManager.PERMISSION_GRANTED;
5230                        }
5231                    } else {
5232                        return PackageManager.PERMISSION_GRANTED;
5233                    }
5234                }
5235                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5236                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5237                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5238                    return PackageManager.PERMISSION_GRANTED;
5239                }
5240            }
5241        }
5242
5243        return PackageManager.PERMISSION_DENIED;
5244    }
5245
5246    @Override
5247    public int checkUidPermission(String permName, int uid) {
5248        final int callingUid = Binder.getCallingUid();
5249        final int callingUserId = UserHandle.getUserId(callingUid);
5250        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5251        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5252        final int userId = UserHandle.getUserId(uid);
5253        if (!sUserManager.exists(userId)) {
5254            return PackageManager.PERMISSION_DENIED;
5255        }
5256
5257        synchronized (mPackages) {
5258            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5259            if (obj != null) {
5260                if (obj instanceof SharedUserSetting) {
5261                    if (isCallerInstantApp) {
5262                        return PackageManager.PERMISSION_DENIED;
5263                    }
5264                } else if (obj instanceof PackageSetting) {
5265                    final PackageSetting ps = (PackageSetting) obj;
5266                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5267                        return PackageManager.PERMISSION_DENIED;
5268                    }
5269                }
5270                final SettingBase settingBase = (SettingBase) obj;
5271                final PermissionsState permissionsState = settingBase.getPermissionsState();
5272                if (permissionsState.hasPermission(permName, userId)) {
5273                    if (isUidInstantApp) {
5274                        BasePermission bp = mSettings.mPermissions.get(permName);
5275                        if (bp != null && bp.isInstant()) {
5276                            return PackageManager.PERMISSION_GRANTED;
5277                        }
5278                    } else {
5279                        return PackageManager.PERMISSION_GRANTED;
5280                    }
5281                }
5282                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5283                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5284                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5285                    return PackageManager.PERMISSION_GRANTED;
5286                }
5287            } else {
5288                ArraySet<String> perms = mSystemPermissions.get(uid);
5289                if (perms != null) {
5290                    if (perms.contains(permName)) {
5291                        return PackageManager.PERMISSION_GRANTED;
5292                    }
5293                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5294                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5295                        return PackageManager.PERMISSION_GRANTED;
5296                    }
5297                }
5298            }
5299        }
5300
5301        return PackageManager.PERMISSION_DENIED;
5302    }
5303
5304    @Override
5305    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5306        if (UserHandle.getCallingUserId() != userId) {
5307            mContext.enforceCallingPermission(
5308                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5309                    "isPermissionRevokedByPolicy for user " + userId);
5310        }
5311
5312        if (checkPermission(permission, packageName, userId)
5313                == PackageManager.PERMISSION_GRANTED) {
5314            return false;
5315        }
5316
5317        final int callingUid = Binder.getCallingUid();
5318        if (getInstantAppPackageName(callingUid) != null) {
5319            if (!isCallerSameApp(packageName, callingUid)) {
5320                return false;
5321            }
5322        } else {
5323            if (isInstantApp(packageName, userId)) {
5324                return false;
5325            }
5326        }
5327
5328        final long identity = Binder.clearCallingIdentity();
5329        try {
5330            final int flags = getPermissionFlags(permission, packageName, userId);
5331            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5332        } finally {
5333            Binder.restoreCallingIdentity(identity);
5334        }
5335    }
5336
5337    @Override
5338    public String getPermissionControllerPackageName() {
5339        synchronized (mPackages) {
5340            return mRequiredInstallerPackage;
5341        }
5342    }
5343
5344    /**
5345     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5346     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5347     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5348     * @param message the message to log on security exception
5349     */
5350    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5351            boolean checkShell, String message) {
5352        if (userId < 0) {
5353            throw new IllegalArgumentException("Invalid userId " + userId);
5354        }
5355        if (checkShell) {
5356            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5357        }
5358        if (userId == UserHandle.getUserId(callingUid)) return;
5359        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5360            if (requireFullPermission) {
5361                mContext.enforceCallingOrSelfPermission(
5362                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5363            } else {
5364                try {
5365                    mContext.enforceCallingOrSelfPermission(
5366                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5367                } catch (SecurityException se) {
5368                    mContext.enforceCallingOrSelfPermission(
5369                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5370                }
5371            }
5372        }
5373    }
5374
5375    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5376        if (callingUid == Process.SHELL_UID) {
5377            if (userHandle >= 0
5378                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5379                throw new SecurityException("Shell does not have permission to access user "
5380                        + userHandle);
5381            } else if (userHandle < 0) {
5382                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5383                        + Debug.getCallers(3));
5384            }
5385        }
5386    }
5387
5388    private BasePermission findPermissionTreeLP(String permName) {
5389        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5390            if (permName.startsWith(bp.name) &&
5391                    permName.length() > bp.name.length() &&
5392                    permName.charAt(bp.name.length()) == '.') {
5393                return bp;
5394            }
5395        }
5396        return null;
5397    }
5398
5399    private BasePermission checkPermissionTreeLP(String permName) {
5400        if (permName != null) {
5401            BasePermission bp = findPermissionTreeLP(permName);
5402            if (bp != null) {
5403                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5404                    return bp;
5405                }
5406                throw new SecurityException("Calling uid "
5407                        + Binder.getCallingUid()
5408                        + " is not allowed to add to permission tree "
5409                        + bp.name + " owned by uid " + bp.uid);
5410            }
5411        }
5412        throw new SecurityException("No permission tree found for " + permName);
5413    }
5414
5415    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5416        if (s1 == null) {
5417            return s2 == null;
5418        }
5419        if (s2 == null) {
5420            return false;
5421        }
5422        if (s1.getClass() != s2.getClass()) {
5423            return false;
5424        }
5425        return s1.equals(s2);
5426    }
5427
5428    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5429        if (pi1.icon != pi2.icon) return false;
5430        if (pi1.logo != pi2.logo) return false;
5431        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5432        if (!compareStrings(pi1.name, pi2.name)) return false;
5433        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5434        // We'll take care of setting this one.
5435        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5436        // These are not currently stored in settings.
5437        //if (!compareStrings(pi1.group, pi2.group)) return false;
5438        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5439        //if (pi1.labelRes != pi2.labelRes) return false;
5440        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5441        return true;
5442    }
5443
5444    int permissionInfoFootprint(PermissionInfo info) {
5445        int size = info.name.length();
5446        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5447        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5448        return size;
5449    }
5450
5451    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5452        int size = 0;
5453        for (BasePermission perm : mSettings.mPermissions.values()) {
5454            if (perm.uid == tree.uid) {
5455                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5456            }
5457        }
5458        return size;
5459    }
5460
5461    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5462        // We calculate the max size of permissions defined by this uid and throw
5463        // if that plus the size of 'info' would exceed our stated maximum.
5464        if (tree.uid != Process.SYSTEM_UID) {
5465            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5466            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5467                throw new SecurityException("Permission tree size cap exceeded");
5468            }
5469        }
5470    }
5471
5472    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5473        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5474            throw new SecurityException("Instant apps can't add permissions");
5475        }
5476        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5477            throw new SecurityException("Label must be specified in permission");
5478        }
5479        BasePermission tree = checkPermissionTreeLP(info.name);
5480        BasePermission bp = mSettings.mPermissions.get(info.name);
5481        boolean added = bp == null;
5482        boolean changed = true;
5483        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5484        if (added) {
5485            enforcePermissionCapLocked(info, tree);
5486            bp = new BasePermission(info.name, tree.sourcePackage,
5487                    BasePermission.TYPE_DYNAMIC);
5488        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5489            throw new SecurityException(
5490                    "Not allowed to modify non-dynamic permission "
5491                    + info.name);
5492        } else {
5493            if (bp.protectionLevel == fixedLevel
5494                    && bp.perm.owner.equals(tree.perm.owner)
5495                    && bp.uid == tree.uid
5496                    && comparePermissionInfos(bp.perm.info, info)) {
5497                changed = false;
5498            }
5499        }
5500        bp.protectionLevel = fixedLevel;
5501        info = new PermissionInfo(info);
5502        info.protectionLevel = fixedLevel;
5503        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5504        bp.perm.info.packageName = tree.perm.info.packageName;
5505        bp.uid = tree.uid;
5506        if (added) {
5507            mSettings.mPermissions.put(info.name, bp);
5508        }
5509        if (changed) {
5510            if (!async) {
5511                mSettings.writeLPr();
5512            } else {
5513                scheduleWriteSettingsLocked();
5514            }
5515        }
5516        return added;
5517    }
5518
5519    @Override
5520    public boolean addPermission(PermissionInfo info) {
5521        synchronized (mPackages) {
5522            return addPermissionLocked(info, false);
5523        }
5524    }
5525
5526    @Override
5527    public boolean addPermissionAsync(PermissionInfo info) {
5528        synchronized (mPackages) {
5529            return addPermissionLocked(info, true);
5530        }
5531    }
5532
5533    @Override
5534    public void removePermission(String name) {
5535        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5536            throw new SecurityException("Instant applications don't have access to this method");
5537        }
5538        synchronized (mPackages) {
5539            checkPermissionTreeLP(name);
5540            BasePermission bp = mSettings.mPermissions.get(name);
5541            if (bp != null) {
5542                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5543                    throw new SecurityException(
5544                            "Not allowed to modify non-dynamic permission "
5545                            + name);
5546                }
5547                mSettings.mPermissions.remove(name);
5548                mSettings.writeLPr();
5549            }
5550        }
5551    }
5552
5553    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5554            PackageParser.Package pkg, BasePermission bp) {
5555        int index = pkg.requestedPermissions.indexOf(bp.name);
5556        if (index == -1) {
5557            throw new SecurityException("Package " + pkg.packageName
5558                    + " has not requested permission " + bp.name);
5559        }
5560        if (!bp.isRuntime() && !bp.isDevelopment()) {
5561            throw new SecurityException("Permission " + bp.name
5562                    + " is not a changeable permission type");
5563        }
5564    }
5565
5566    @Override
5567    public void grantRuntimePermission(String packageName, String name, final int userId) {
5568        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5569    }
5570
5571    private void grantRuntimePermission(String packageName, String name, final int userId,
5572            boolean overridePolicy) {
5573        if (!sUserManager.exists(userId)) {
5574            Log.e(TAG, "No such user:" + userId);
5575            return;
5576        }
5577        final int callingUid = Binder.getCallingUid();
5578
5579        mContext.enforceCallingOrSelfPermission(
5580                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5581                "grantRuntimePermission");
5582
5583        enforceCrossUserPermission(callingUid, userId,
5584                true /* requireFullPermission */, true /* checkShell */,
5585                "grantRuntimePermission");
5586
5587        final int uid;
5588        final PackageSetting ps;
5589
5590        synchronized (mPackages) {
5591            final PackageParser.Package pkg = mPackages.get(packageName);
5592            if (pkg == null) {
5593                throw new IllegalArgumentException("Unknown package: " + packageName);
5594            }
5595            final BasePermission bp = mSettings.mPermissions.get(name);
5596            if (bp == null) {
5597                throw new IllegalArgumentException("Unknown permission: " + name);
5598            }
5599            ps = (PackageSetting) pkg.mExtras;
5600            if (ps == null
5601                    || filterAppAccessLPr(ps, callingUid, userId)) {
5602                throw new IllegalArgumentException("Unknown package: " + packageName);
5603            }
5604
5605            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5606
5607            // If a permission review is required for legacy apps we represent
5608            // their permissions as always granted runtime ones since we need
5609            // to keep the review required permission flag per user while an
5610            // install permission's state is shared across all users.
5611            if (mPermissionReviewRequired
5612                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5613                    && bp.isRuntime()) {
5614                return;
5615            }
5616
5617            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5618
5619            final PermissionsState permissionsState = ps.getPermissionsState();
5620
5621            final int flags = permissionsState.getPermissionFlags(name, userId);
5622            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5623                throw new SecurityException("Cannot grant system fixed permission "
5624                        + name + " for package " + packageName);
5625            }
5626            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5627                throw new SecurityException("Cannot grant policy fixed permission "
5628                        + name + " for package " + packageName);
5629            }
5630
5631            if (bp.isDevelopment()) {
5632                // Development permissions must be handled specially, since they are not
5633                // normal runtime permissions.  For now they apply to all users.
5634                if (permissionsState.grantInstallPermission(bp) !=
5635                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5636                    scheduleWriteSettingsLocked();
5637                }
5638                return;
5639            }
5640
5641            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5642                throw new SecurityException("Cannot grant non-ephemeral permission"
5643                        + name + " for package " + packageName);
5644            }
5645
5646            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5647                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5648                return;
5649            }
5650
5651            final int result = permissionsState.grantRuntimePermission(bp, userId);
5652            switch (result) {
5653                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5654                    return;
5655                }
5656
5657                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5658                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5659                    mHandler.post(new Runnable() {
5660                        @Override
5661                        public void run() {
5662                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5663                        }
5664                    });
5665                }
5666                break;
5667            }
5668
5669            if (bp.isRuntime()) {
5670                logPermissionGranted(mContext, name, packageName);
5671            }
5672
5673            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5674
5675            // Not critical if that is lost - app has to request again.
5676            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5677        }
5678
5679        // Only need to do this if user is initialized. Otherwise it's a new user
5680        // and there are no processes running as the user yet and there's no need
5681        // to make an expensive call to remount processes for the changed permissions.
5682        if (READ_EXTERNAL_STORAGE.equals(name)
5683                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5684            final long token = Binder.clearCallingIdentity();
5685            try {
5686                if (sUserManager.isInitialized(userId)) {
5687                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5688                            StorageManagerInternal.class);
5689                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5690                }
5691            } finally {
5692                Binder.restoreCallingIdentity(token);
5693            }
5694        }
5695    }
5696
5697    @Override
5698    public void revokeRuntimePermission(String packageName, String name, int userId) {
5699        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5700    }
5701
5702    private void revokeRuntimePermission(String packageName, String name, int userId,
5703            boolean overridePolicy) {
5704        if (!sUserManager.exists(userId)) {
5705            Log.e(TAG, "No such user:" + userId);
5706            return;
5707        }
5708
5709        mContext.enforceCallingOrSelfPermission(
5710                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5711                "revokeRuntimePermission");
5712
5713        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5714                true /* requireFullPermission */, true /* checkShell */,
5715                "revokeRuntimePermission");
5716
5717        final int appId;
5718
5719        synchronized (mPackages) {
5720            final PackageParser.Package pkg = mPackages.get(packageName);
5721            if (pkg == null) {
5722                throw new IllegalArgumentException("Unknown package: " + packageName);
5723            }
5724            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5725            if (ps == null
5726                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5727                throw new IllegalArgumentException("Unknown package: " + packageName);
5728            }
5729            final BasePermission bp = mSettings.mPermissions.get(name);
5730            if (bp == null) {
5731                throw new IllegalArgumentException("Unknown permission: " + name);
5732            }
5733
5734            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5735
5736            // If a permission review is required for legacy apps we represent
5737            // their permissions as always granted runtime ones since we need
5738            // to keep the review required permission flag per user while an
5739            // install permission's state is shared across all users.
5740            if (mPermissionReviewRequired
5741                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5742                    && bp.isRuntime()) {
5743                return;
5744            }
5745
5746            final PermissionsState permissionsState = ps.getPermissionsState();
5747
5748            final int flags = permissionsState.getPermissionFlags(name, userId);
5749            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5750                throw new SecurityException("Cannot revoke system fixed permission "
5751                        + name + " for package " + packageName);
5752            }
5753            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5754                throw new SecurityException("Cannot revoke policy fixed permission "
5755                        + name + " for package " + packageName);
5756            }
5757
5758            if (bp.isDevelopment()) {
5759                // Development permissions must be handled specially, since they are not
5760                // normal runtime permissions.  For now they apply to all users.
5761                if (permissionsState.revokeInstallPermission(bp) !=
5762                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5763                    scheduleWriteSettingsLocked();
5764                }
5765                return;
5766            }
5767
5768            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5769                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5770                return;
5771            }
5772
5773            if (bp.isRuntime()) {
5774                logPermissionRevoked(mContext, name, packageName);
5775            }
5776
5777            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5778
5779            // Critical, after this call app should never have the permission.
5780            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5781
5782            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5783        }
5784
5785        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5786    }
5787
5788    /**
5789     * Get the first event id for the permission.
5790     *
5791     * <p>There are four events for each permission: <ul>
5792     *     <li>Request permission: first id + 0</li>
5793     *     <li>Grant permission: first id + 1</li>
5794     *     <li>Request for permission denied: first id + 2</li>
5795     *     <li>Revoke permission: first id + 3</li>
5796     * </ul></p>
5797     *
5798     * @param name name of the permission
5799     *
5800     * @return The first event id for the permission
5801     */
5802    private static int getBaseEventId(@NonNull String name) {
5803        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5804
5805        if (eventIdIndex == -1) {
5806            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5807                    || Build.IS_USER) {
5808                Log.i(TAG, "Unknown permission " + name);
5809
5810                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5811            } else {
5812                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5813                //
5814                // Also update
5815                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5816                // - metrics_constants.proto
5817                throw new IllegalStateException("Unknown permission " + name);
5818            }
5819        }
5820
5821        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5822    }
5823
5824    /**
5825     * Log that a permission was revoked.
5826     *
5827     * @param context Context of the caller
5828     * @param name name of the permission
5829     * @param packageName package permission if for
5830     */
5831    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5832            @NonNull String packageName) {
5833        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5834    }
5835
5836    /**
5837     * Log that a permission request was granted.
5838     *
5839     * @param context Context of the caller
5840     * @param name name of the permission
5841     * @param packageName package permission if for
5842     */
5843    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5844            @NonNull String packageName) {
5845        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5846    }
5847
5848    @Override
5849    public void resetRuntimePermissions() {
5850        mContext.enforceCallingOrSelfPermission(
5851                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5852                "revokeRuntimePermission");
5853
5854        int callingUid = Binder.getCallingUid();
5855        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5856            mContext.enforceCallingOrSelfPermission(
5857                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5858                    "resetRuntimePermissions");
5859        }
5860
5861        synchronized (mPackages) {
5862            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5863            for (int userId : UserManagerService.getInstance().getUserIds()) {
5864                final int packageCount = mPackages.size();
5865                for (int i = 0; i < packageCount; i++) {
5866                    PackageParser.Package pkg = mPackages.valueAt(i);
5867                    if (!(pkg.mExtras instanceof PackageSetting)) {
5868                        continue;
5869                    }
5870                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5871                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5872                }
5873            }
5874        }
5875    }
5876
5877    @Override
5878    public int getPermissionFlags(String name, String packageName, int userId) {
5879        if (!sUserManager.exists(userId)) {
5880            return 0;
5881        }
5882
5883        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5884
5885        final int callingUid = Binder.getCallingUid();
5886        enforceCrossUserPermission(callingUid, userId,
5887                true /* requireFullPermission */, false /* checkShell */,
5888                "getPermissionFlags");
5889
5890        synchronized (mPackages) {
5891            final PackageParser.Package pkg = mPackages.get(packageName);
5892            if (pkg == null) {
5893                return 0;
5894            }
5895            final BasePermission bp = mSettings.mPermissions.get(name);
5896            if (bp == null) {
5897                return 0;
5898            }
5899            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5900            if (ps == null
5901                    || filterAppAccessLPr(ps, callingUid, userId)) {
5902                return 0;
5903            }
5904            PermissionsState permissionsState = ps.getPermissionsState();
5905            return permissionsState.getPermissionFlags(name, userId);
5906        }
5907    }
5908
5909    @Override
5910    public void updatePermissionFlags(String name, String packageName, int flagMask,
5911            int flagValues, int userId) {
5912        if (!sUserManager.exists(userId)) {
5913            return;
5914        }
5915
5916        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5917
5918        final int callingUid = Binder.getCallingUid();
5919        enforceCrossUserPermission(callingUid, userId,
5920                true /* requireFullPermission */, true /* checkShell */,
5921                "updatePermissionFlags");
5922
5923        // Only the system can change these flags and nothing else.
5924        if (getCallingUid() != Process.SYSTEM_UID) {
5925            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5926            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5927            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5928            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5929            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5930        }
5931
5932        synchronized (mPackages) {
5933            final PackageParser.Package pkg = mPackages.get(packageName);
5934            if (pkg == null) {
5935                throw new IllegalArgumentException("Unknown package: " + packageName);
5936            }
5937            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5938            if (ps == null
5939                    || filterAppAccessLPr(ps, callingUid, userId)) {
5940                throw new IllegalArgumentException("Unknown package: " + packageName);
5941            }
5942
5943            final BasePermission bp = mSettings.mPermissions.get(name);
5944            if (bp == null) {
5945                throw new IllegalArgumentException("Unknown permission: " + name);
5946            }
5947
5948            PermissionsState permissionsState = ps.getPermissionsState();
5949
5950            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5951
5952            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5953                // Install and runtime permissions are stored in different places,
5954                // so figure out what permission changed and persist the change.
5955                if (permissionsState.getInstallPermissionState(name) != null) {
5956                    scheduleWriteSettingsLocked();
5957                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5958                        || hadState) {
5959                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5960                }
5961            }
5962        }
5963    }
5964
5965    /**
5966     * Update the permission flags for all packages and runtime permissions of a user in order
5967     * to allow device or profile owner to remove POLICY_FIXED.
5968     */
5969    @Override
5970    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5971        if (!sUserManager.exists(userId)) {
5972            return;
5973        }
5974
5975        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5976
5977        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5978                true /* requireFullPermission */, true /* checkShell */,
5979                "updatePermissionFlagsForAllApps");
5980
5981        // Only the system can change system fixed flags.
5982        if (getCallingUid() != Process.SYSTEM_UID) {
5983            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5984            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5985        }
5986
5987        synchronized (mPackages) {
5988            boolean changed = false;
5989            final int packageCount = mPackages.size();
5990            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5991                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5992                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5993                if (ps == null) {
5994                    continue;
5995                }
5996                PermissionsState permissionsState = ps.getPermissionsState();
5997                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5998                        userId, flagMask, flagValues);
5999            }
6000            if (changed) {
6001                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6002            }
6003        }
6004    }
6005
6006    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6007        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6008                != PackageManager.PERMISSION_GRANTED
6009            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6010                != PackageManager.PERMISSION_GRANTED) {
6011            throw new SecurityException(message + " requires "
6012                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6013                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6014        }
6015    }
6016
6017    @Override
6018    public boolean shouldShowRequestPermissionRationale(String permissionName,
6019            String packageName, int userId) {
6020        if (UserHandle.getCallingUserId() != userId) {
6021            mContext.enforceCallingPermission(
6022                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6023                    "canShowRequestPermissionRationale for user " + userId);
6024        }
6025
6026        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6027        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6028            return false;
6029        }
6030
6031        if (checkPermission(permissionName, packageName, userId)
6032                == PackageManager.PERMISSION_GRANTED) {
6033            return false;
6034        }
6035
6036        final int flags;
6037
6038        final long identity = Binder.clearCallingIdentity();
6039        try {
6040            flags = getPermissionFlags(permissionName,
6041                    packageName, userId);
6042        } finally {
6043            Binder.restoreCallingIdentity(identity);
6044        }
6045
6046        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6047                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6048                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6049
6050        if ((flags & fixedFlags) != 0) {
6051            return false;
6052        }
6053
6054        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6055    }
6056
6057    @Override
6058    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6059        mContext.enforceCallingOrSelfPermission(
6060                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6061                "addOnPermissionsChangeListener");
6062
6063        synchronized (mPackages) {
6064            mOnPermissionChangeListeners.addListenerLocked(listener);
6065        }
6066    }
6067
6068    @Override
6069    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6070        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6071            throw new SecurityException("Instant applications don't have access to this method");
6072        }
6073        synchronized (mPackages) {
6074            mOnPermissionChangeListeners.removeListenerLocked(listener);
6075        }
6076    }
6077
6078    @Override
6079    public boolean isProtectedBroadcast(String actionName) {
6080        // allow instant applications
6081        synchronized (mProtectedBroadcasts) {
6082            if (mProtectedBroadcasts.contains(actionName)) {
6083                return true;
6084            } else if (actionName != null) {
6085                // TODO: remove these terrible hacks
6086                if (actionName.startsWith("android.net.netmon.lingerExpired")
6087                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6088                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6089                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6090                    return true;
6091                }
6092            }
6093        }
6094        return false;
6095    }
6096
6097    @Override
6098    public int checkSignatures(String pkg1, String pkg2) {
6099        synchronized (mPackages) {
6100            final PackageParser.Package p1 = mPackages.get(pkg1);
6101            final PackageParser.Package p2 = mPackages.get(pkg2);
6102            if (p1 == null || p1.mExtras == null
6103                    || p2 == null || p2.mExtras == null) {
6104                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6105            }
6106            final int callingUid = Binder.getCallingUid();
6107            final int callingUserId = UserHandle.getUserId(callingUid);
6108            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6109            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6110            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6111                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6112                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6113            }
6114            return compareSignatures(p1.mSignatures, p2.mSignatures);
6115        }
6116    }
6117
6118    @Override
6119    public int checkUidSignatures(int uid1, int uid2) {
6120        final int callingUid = Binder.getCallingUid();
6121        final int callingUserId = UserHandle.getUserId(callingUid);
6122        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6123        // Map to base uids.
6124        uid1 = UserHandle.getAppId(uid1);
6125        uid2 = UserHandle.getAppId(uid2);
6126        // reader
6127        synchronized (mPackages) {
6128            Signature[] s1;
6129            Signature[] s2;
6130            Object obj = mSettings.getUserIdLPr(uid1);
6131            if (obj != null) {
6132                if (obj instanceof SharedUserSetting) {
6133                    if (isCallerInstantApp) {
6134                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6135                    }
6136                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6137                } else if (obj instanceof PackageSetting) {
6138                    final PackageSetting ps = (PackageSetting) obj;
6139                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6140                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6141                    }
6142                    s1 = ps.signatures.mSignatures;
6143                } else {
6144                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6145                }
6146            } else {
6147                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6148            }
6149            obj = mSettings.getUserIdLPr(uid2);
6150            if (obj != null) {
6151                if (obj instanceof SharedUserSetting) {
6152                    if (isCallerInstantApp) {
6153                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6154                    }
6155                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6156                } else if (obj instanceof PackageSetting) {
6157                    final PackageSetting ps = (PackageSetting) obj;
6158                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6159                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6160                    }
6161                    s2 = ps.signatures.mSignatures;
6162                } else {
6163                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6164                }
6165            } else {
6166                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6167            }
6168            return compareSignatures(s1, s2);
6169        }
6170    }
6171
6172    /**
6173     * This method should typically only be used when granting or revoking
6174     * permissions, since the app may immediately restart after this call.
6175     * <p>
6176     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6177     * guard your work against the app being relaunched.
6178     */
6179    private void killUid(int appId, int userId, String reason) {
6180        final long identity = Binder.clearCallingIdentity();
6181        try {
6182            IActivityManager am = ActivityManager.getService();
6183            if (am != null) {
6184                try {
6185                    am.killUid(appId, userId, reason);
6186                } catch (RemoteException e) {
6187                    /* ignore - same process */
6188                }
6189            }
6190        } finally {
6191            Binder.restoreCallingIdentity(identity);
6192        }
6193    }
6194
6195    /**
6196     * Compares two sets of signatures. Returns:
6197     * <br />
6198     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6199     * <br />
6200     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6201     * <br />
6202     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6203     * <br />
6204     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6205     * <br />
6206     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6207     */
6208    static int compareSignatures(Signature[] s1, Signature[] s2) {
6209        if (s1 == null) {
6210            return s2 == null
6211                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6212                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6213        }
6214
6215        if (s2 == null) {
6216            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6217        }
6218
6219        if (s1.length != s2.length) {
6220            return PackageManager.SIGNATURE_NO_MATCH;
6221        }
6222
6223        // Since both signature sets are of size 1, we can compare without HashSets.
6224        if (s1.length == 1) {
6225            return s1[0].equals(s2[0]) ?
6226                    PackageManager.SIGNATURE_MATCH :
6227                    PackageManager.SIGNATURE_NO_MATCH;
6228        }
6229
6230        ArraySet<Signature> set1 = new ArraySet<Signature>();
6231        for (Signature sig : s1) {
6232            set1.add(sig);
6233        }
6234        ArraySet<Signature> set2 = new ArraySet<Signature>();
6235        for (Signature sig : s2) {
6236            set2.add(sig);
6237        }
6238        // Make sure s2 contains all signatures in s1.
6239        if (set1.equals(set2)) {
6240            return PackageManager.SIGNATURE_MATCH;
6241        }
6242        return PackageManager.SIGNATURE_NO_MATCH;
6243    }
6244
6245    /**
6246     * If the database version for this type of package (internal storage or
6247     * external storage) is less than the version where package signatures
6248     * were updated, return true.
6249     */
6250    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6251        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6252        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6253    }
6254
6255    /**
6256     * Used for backward compatibility to make sure any packages with
6257     * certificate chains get upgraded to the new style. {@code existingSigs}
6258     * will be in the old format (since they were stored on disk from before the
6259     * system upgrade) and {@code scannedSigs} will be in the newer format.
6260     */
6261    private int compareSignaturesCompat(PackageSignatures existingSigs,
6262            PackageParser.Package scannedPkg) {
6263        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6264            return PackageManager.SIGNATURE_NO_MATCH;
6265        }
6266
6267        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6268        for (Signature sig : existingSigs.mSignatures) {
6269            existingSet.add(sig);
6270        }
6271        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6272        for (Signature sig : scannedPkg.mSignatures) {
6273            try {
6274                Signature[] chainSignatures = sig.getChainSignatures();
6275                for (Signature chainSig : chainSignatures) {
6276                    scannedCompatSet.add(chainSig);
6277                }
6278            } catch (CertificateEncodingException e) {
6279                scannedCompatSet.add(sig);
6280            }
6281        }
6282        /*
6283         * Make sure the expanded scanned set contains all signatures in the
6284         * existing one.
6285         */
6286        if (scannedCompatSet.equals(existingSet)) {
6287            // Migrate the old signatures to the new scheme.
6288            existingSigs.assignSignatures(scannedPkg.mSignatures);
6289            // The new KeySets will be re-added later in the scanning process.
6290            synchronized (mPackages) {
6291                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6292            }
6293            return PackageManager.SIGNATURE_MATCH;
6294        }
6295        return PackageManager.SIGNATURE_NO_MATCH;
6296    }
6297
6298    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6299        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6300        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6301    }
6302
6303    private int compareSignaturesRecover(PackageSignatures existingSigs,
6304            PackageParser.Package scannedPkg) {
6305        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6306            return PackageManager.SIGNATURE_NO_MATCH;
6307        }
6308
6309        String msg = null;
6310        try {
6311            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6312                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6313                        + scannedPkg.packageName);
6314                return PackageManager.SIGNATURE_MATCH;
6315            }
6316        } catch (CertificateException e) {
6317            msg = e.getMessage();
6318        }
6319
6320        logCriticalInfo(Log.INFO,
6321                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6322        return PackageManager.SIGNATURE_NO_MATCH;
6323    }
6324
6325    @Override
6326    public List<String> getAllPackages() {
6327        final int callingUid = Binder.getCallingUid();
6328        final int callingUserId = UserHandle.getUserId(callingUid);
6329        synchronized (mPackages) {
6330            if (canViewInstantApps(callingUid, callingUserId)) {
6331                return new ArrayList<String>(mPackages.keySet());
6332            }
6333            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6334            final List<String> result = new ArrayList<>();
6335            if (instantAppPkgName != null) {
6336                // caller is an instant application; filter unexposed applications
6337                for (PackageParser.Package pkg : mPackages.values()) {
6338                    if (!pkg.visibleToInstantApps) {
6339                        continue;
6340                    }
6341                    result.add(pkg.packageName);
6342                }
6343            } else {
6344                // caller is a normal application; filter instant applications
6345                for (PackageParser.Package pkg : mPackages.values()) {
6346                    final PackageSetting ps =
6347                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6348                    if (ps != null
6349                            && ps.getInstantApp(callingUserId)
6350                            && !mInstantAppRegistry.isInstantAccessGranted(
6351                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6352                        continue;
6353                    }
6354                    result.add(pkg.packageName);
6355                }
6356            }
6357            return result;
6358        }
6359    }
6360
6361    @Override
6362    public String[] getPackagesForUid(int uid) {
6363        final int callingUid = Binder.getCallingUid();
6364        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6365        final int userId = UserHandle.getUserId(uid);
6366        uid = UserHandle.getAppId(uid);
6367        // reader
6368        synchronized (mPackages) {
6369            Object obj = mSettings.getUserIdLPr(uid);
6370            if (obj instanceof SharedUserSetting) {
6371                if (isCallerInstantApp) {
6372                    return null;
6373                }
6374                final SharedUserSetting sus = (SharedUserSetting) obj;
6375                final int N = sus.packages.size();
6376                String[] res = new String[N];
6377                final Iterator<PackageSetting> it = sus.packages.iterator();
6378                int i = 0;
6379                while (it.hasNext()) {
6380                    PackageSetting ps = it.next();
6381                    if (ps.getInstalled(userId)) {
6382                        res[i++] = ps.name;
6383                    } else {
6384                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6385                    }
6386                }
6387                return res;
6388            } else if (obj instanceof PackageSetting) {
6389                final PackageSetting ps = (PackageSetting) obj;
6390                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6391                    return new String[]{ps.name};
6392                }
6393            }
6394        }
6395        return null;
6396    }
6397
6398    @Override
6399    public String getNameForUid(int uid) {
6400        final int callingUid = Binder.getCallingUid();
6401        if (getInstantAppPackageName(callingUid) != null) {
6402            return null;
6403        }
6404        synchronized (mPackages) {
6405            return getNameForUidLocked(callingUid, uid);
6406        }
6407    }
6408
6409    @Override
6410    public String[] getNamesForUids(int[] uids) {
6411        if (uids == null || uids.length == 0) {
6412            return null;
6413        }
6414        final int callingUid = Binder.getCallingUid();
6415        if (getInstantAppPackageName(callingUid) != null) {
6416            return null;
6417        }
6418        final String[] names = new String[uids.length];
6419        synchronized (mPackages) {
6420            for (int i = uids.length - 1; i >= 0; i--) {
6421                final int uid = uids[i];
6422                names[i] = getNameForUidLocked(callingUid, uid);
6423            }
6424        }
6425        return names;
6426    }
6427
6428    private String getNameForUidLocked(int callingUid, int uid) {
6429        Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6430        if (obj instanceof SharedUserSetting) {
6431            final SharedUserSetting sus = (SharedUserSetting) obj;
6432            return sus.name + ":" + sus.userId;
6433        } else if (obj instanceof PackageSetting) {
6434            final PackageSetting ps = (PackageSetting) obj;
6435            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6436                return null;
6437            }
6438            return ps.name;
6439        }
6440        return null;
6441    }
6442
6443    @Override
6444    public int getUidForSharedUser(String sharedUserName) {
6445        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6446            return -1;
6447        }
6448        if (sharedUserName == null) {
6449            return -1;
6450        }
6451        // reader
6452        synchronized (mPackages) {
6453            SharedUserSetting suid;
6454            try {
6455                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6456                if (suid != null) {
6457                    return suid.userId;
6458                }
6459            } catch (PackageManagerException ignore) {
6460                // can't happen, but, still need to catch it
6461            }
6462            return -1;
6463        }
6464    }
6465
6466    @Override
6467    public int getFlagsForUid(int uid) {
6468        final int callingUid = Binder.getCallingUid();
6469        if (getInstantAppPackageName(callingUid) != null) {
6470            return 0;
6471        }
6472        synchronized (mPackages) {
6473            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6474            if (obj instanceof SharedUserSetting) {
6475                final SharedUserSetting sus = (SharedUserSetting) obj;
6476                return sus.pkgFlags;
6477            } else if (obj instanceof PackageSetting) {
6478                final PackageSetting ps = (PackageSetting) obj;
6479                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6480                    return 0;
6481                }
6482                return ps.pkgFlags;
6483            }
6484        }
6485        return 0;
6486    }
6487
6488    @Override
6489    public int getPrivateFlagsForUid(int uid) {
6490        final int callingUid = Binder.getCallingUid();
6491        if (getInstantAppPackageName(callingUid) != null) {
6492            return 0;
6493        }
6494        synchronized (mPackages) {
6495            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6496            if (obj instanceof SharedUserSetting) {
6497                final SharedUserSetting sus = (SharedUserSetting) obj;
6498                return sus.pkgPrivateFlags;
6499            } else if (obj instanceof PackageSetting) {
6500                final PackageSetting ps = (PackageSetting) obj;
6501                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6502                    return 0;
6503                }
6504                return ps.pkgPrivateFlags;
6505            }
6506        }
6507        return 0;
6508    }
6509
6510    @Override
6511    public boolean isUidPrivileged(int uid) {
6512        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6513            return false;
6514        }
6515        uid = UserHandle.getAppId(uid);
6516        // reader
6517        synchronized (mPackages) {
6518            Object obj = mSettings.getUserIdLPr(uid);
6519            if (obj instanceof SharedUserSetting) {
6520                final SharedUserSetting sus = (SharedUserSetting) obj;
6521                final Iterator<PackageSetting> it = sus.packages.iterator();
6522                while (it.hasNext()) {
6523                    if (it.next().isPrivileged()) {
6524                        return true;
6525                    }
6526                }
6527            } else if (obj instanceof PackageSetting) {
6528                final PackageSetting ps = (PackageSetting) obj;
6529                return ps.isPrivileged();
6530            }
6531        }
6532        return false;
6533    }
6534
6535    @Override
6536    public String[] getAppOpPermissionPackages(String permissionName) {
6537        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6538            return null;
6539        }
6540        synchronized (mPackages) {
6541            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6542            if (pkgs == null) {
6543                return null;
6544            }
6545            return pkgs.toArray(new String[pkgs.size()]);
6546        }
6547    }
6548
6549    @Override
6550    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6551            int flags, int userId) {
6552        return resolveIntentInternal(
6553                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6554    }
6555
6556    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6557            int flags, int userId, boolean resolveForStart) {
6558        try {
6559            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6560
6561            if (!sUserManager.exists(userId)) return null;
6562            final int callingUid = Binder.getCallingUid();
6563            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6564            enforceCrossUserPermission(callingUid, userId,
6565                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6566
6567            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6568            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6569                    flags, callingUid, userId, resolveForStart);
6570            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6571
6572            final ResolveInfo bestChoice =
6573                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6574            return bestChoice;
6575        } finally {
6576            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6577        }
6578    }
6579
6580    @Override
6581    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6582        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6583            throw new SecurityException(
6584                    "findPersistentPreferredActivity can only be run by the system");
6585        }
6586        if (!sUserManager.exists(userId)) {
6587            return null;
6588        }
6589        final int callingUid = Binder.getCallingUid();
6590        intent = updateIntentForResolve(intent);
6591        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6592        final int flags = updateFlagsForResolve(
6593                0, userId, intent, callingUid, false /*includeInstantApps*/);
6594        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6595                userId);
6596        synchronized (mPackages) {
6597            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6598                    userId);
6599        }
6600    }
6601
6602    @Override
6603    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6604            IntentFilter filter, int match, ComponentName activity) {
6605        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6606            return;
6607        }
6608        final int userId = UserHandle.getCallingUserId();
6609        if (DEBUG_PREFERRED) {
6610            Log.v(TAG, "setLastChosenActivity intent=" + intent
6611                + " resolvedType=" + resolvedType
6612                + " flags=" + flags
6613                + " filter=" + filter
6614                + " match=" + match
6615                + " activity=" + activity);
6616            filter.dump(new PrintStreamPrinter(System.out), "    ");
6617        }
6618        intent.setComponent(null);
6619        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6620                userId);
6621        // Find any earlier preferred or last chosen entries and nuke them
6622        findPreferredActivity(intent, resolvedType,
6623                flags, query, 0, false, true, false, userId);
6624        // Add the new activity as the last chosen for this filter
6625        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6626                "Setting last chosen");
6627    }
6628
6629    @Override
6630    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6631        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6632            return null;
6633        }
6634        final int userId = UserHandle.getCallingUserId();
6635        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6636        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6637                userId);
6638        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6639                false, false, false, userId);
6640    }
6641
6642    /**
6643     * Returns whether or not instant apps have been disabled remotely.
6644     */
6645    private boolean isEphemeralDisabled() {
6646        return mEphemeralAppsDisabled;
6647    }
6648
6649    private boolean isInstantAppAllowed(
6650            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6651            boolean skipPackageCheck) {
6652        if (mInstantAppResolverConnection == null) {
6653            return false;
6654        }
6655        if (mInstantAppInstallerActivity == null) {
6656            return false;
6657        }
6658        if (intent.getComponent() != null) {
6659            return false;
6660        }
6661        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6662            return false;
6663        }
6664        if (!skipPackageCheck && intent.getPackage() != null) {
6665            return false;
6666        }
6667        final boolean isWebUri = hasWebURI(intent);
6668        if (!isWebUri || intent.getData().getHost() == null) {
6669            return false;
6670        }
6671        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6672        // Or if there's already an ephemeral app installed that handles the action
6673        synchronized (mPackages) {
6674            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6675            for (int n = 0; n < count; n++) {
6676                final ResolveInfo info = resolvedActivities.get(n);
6677                final String packageName = info.activityInfo.packageName;
6678                final PackageSetting ps = mSettings.mPackages.get(packageName);
6679                if (ps != null) {
6680                    // only check domain verification status if the app is not a browser
6681                    if (!info.handleAllWebDataURI) {
6682                        // Try to get the status from User settings first
6683                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6684                        final int status = (int) (packedStatus >> 32);
6685                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6686                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6687                            if (DEBUG_EPHEMERAL) {
6688                                Slog.v(TAG, "DENY instant app;"
6689                                    + " pkg: " + packageName + ", status: " + status);
6690                            }
6691                            return false;
6692                        }
6693                    }
6694                    if (ps.getInstantApp(userId)) {
6695                        if (DEBUG_EPHEMERAL) {
6696                            Slog.v(TAG, "DENY instant app installed;"
6697                                    + " pkg: " + packageName);
6698                        }
6699                        return false;
6700                    }
6701                }
6702            }
6703        }
6704        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6705        return true;
6706    }
6707
6708    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6709            Intent origIntent, String resolvedType, String callingPackage,
6710            Bundle verificationBundle, int userId) {
6711        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6712                new InstantAppRequest(responseObj, origIntent, resolvedType,
6713                        callingPackage, userId, verificationBundle));
6714        mHandler.sendMessage(msg);
6715    }
6716
6717    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6718            int flags, List<ResolveInfo> query, int userId) {
6719        if (query != null) {
6720            final int N = query.size();
6721            if (N == 1) {
6722                return query.get(0);
6723            } else if (N > 1) {
6724                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6725                // If there is more than one activity with the same priority,
6726                // then let the user decide between them.
6727                ResolveInfo r0 = query.get(0);
6728                ResolveInfo r1 = query.get(1);
6729                if (DEBUG_INTENT_MATCHING || debug) {
6730                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6731                            + r1.activityInfo.name + "=" + r1.priority);
6732                }
6733                // If the first activity has a higher priority, or a different
6734                // default, then it is always desirable to pick it.
6735                if (r0.priority != r1.priority
6736                        || r0.preferredOrder != r1.preferredOrder
6737                        || r0.isDefault != r1.isDefault) {
6738                    return query.get(0);
6739                }
6740                // If we have saved a preference for a preferred activity for
6741                // this Intent, use that.
6742                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6743                        flags, query, r0.priority, true, false, debug, userId);
6744                if (ri != null) {
6745                    return ri;
6746                }
6747                // If we have an ephemeral app, use it
6748                for (int i = 0; i < N; i++) {
6749                    ri = query.get(i);
6750                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6751                        final String packageName = ri.activityInfo.packageName;
6752                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6753                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6754                        final int status = (int)(packedStatus >> 32);
6755                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6756                            return ri;
6757                        }
6758                    }
6759                }
6760                ri = new ResolveInfo(mResolveInfo);
6761                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6762                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6763                // If all of the options come from the same package, show the application's
6764                // label and icon instead of the generic resolver's.
6765                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6766                // and then throw away the ResolveInfo itself, meaning that the caller loses
6767                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6768                // a fallback for this case; we only set the target package's resources on
6769                // the ResolveInfo, not the ActivityInfo.
6770                final String intentPackage = intent.getPackage();
6771                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6772                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6773                    ri.resolvePackageName = intentPackage;
6774                    if (userNeedsBadging(userId)) {
6775                        ri.noResourceId = true;
6776                    } else {
6777                        ri.icon = appi.icon;
6778                    }
6779                    ri.iconResourceId = appi.icon;
6780                    ri.labelRes = appi.labelRes;
6781                }
6782                ri.activityInfo.applicationInfo = new ApplicationInfo(
6783                        ri.activityInfo.applicationInfo);
6784                if (userId != 0) {
6785                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6786                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6787                }
6788                // Make sure that the resolver is displayable in car mode
6789                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6790                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6791                return ri;
6792            }
6793        }
6794        return null;
6795    }
6796
6797    /**
6798     * Return true if the given list is not empty and all of its contents have
6799     * an activityInfo with the given package name.
6800     */
6801    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6802        if (ArrayUtils.isEmpty(list)) {
6803            return false;
6804        }
6805        for (int i = 0, N = list.size(); i < N; i++) {
6806            final ResolveInfo ri = list.get(i);
6807            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6808            if (ai == null || !packageName.equals(ai.packageName)) {
6809                return false;
6810            }
6811        }
6812        return true;
6813    }
6814
6815    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6816            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6817        final int N = query.size();
6818        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6819                .get(userId);
6820        // Get the list of persistent preferred activities that handle the intent
6821        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6822        List<PersistentPreferredActivity> pprefs = ppir != null
6823                ? ppir.queryIntent(intent, resolvedType,
6824                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6825                        userId)
6826                : null;
6827        if (pprefs != null && pprefs.size() > 0) {
6828            final int M = pprefs.size();
6829            for (int i=0; i<M; i++) {
6830                final PersistentPreferredActivity ppa = pprefs.get(i);
6831                if (DEBUG_PREFERRED || debug) {
6832                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6833                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6834                            + "\n  component=" + ppa.mComponent);
6835                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6836                }
6837                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6838                        flags | MATCH_DISABLED_COMPONENTS, userId);
6839                if (DEBUG_PREFERRED || debug) {
6840                    Slog.v(TAG, "Found persistent preferred activity:");
6841                    if (ai != null) {
6842                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6843                    } else {
6844                        Slog.v(TAG, "  null");
6845                    }
6846                }
6847                if (ai == null) {
6848                    // This previously registered persistent preferred activity
6849                    // component is no longer known. Ignore it and do NOT remove it.
6850                    continue;
6851                }
6852                for (int j=0; j<N; j++) {
6853                    final ResolveInfo ri = query.get(j);
6854                    if (!ri.activityInfo.applicationInfo.packageName
6855                            .equals(ai.applicationInfo.packageName)) {
6856                        continue;
6857                    }
6858                    if (!ri.activityInfo.name.equals(ai.name)) {
6859                        continue;
6860                    }
6861                    //  Found a persistent preference that can handle the intent.
6862                    if (DEBUG_PREFERRED || debug) {
6863                        Slog.v(TAG, "Returning persistent preferred activity: " +
6864                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6865                    }
6866                    return ri;
6867                }
6868            }
6869        }
6870        return null;
6871    }
6872
6873    // TODO: handle preferred activities missing while user has amnesia
6874    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6875            List<ResolveInfo> query, int priority, boolean always,
6876            boolean removeMatches, boolean debug, int userId) {
6877        if (!sUserManager.exists(userId)) return null;
6878        final int callingUid = Binder.getCallingUid();
6879        flags = updateFlagsForResolve(
6880                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6881        intent = updateIntentForResolve(intent);
6882        // writer
6883        synchronized (mPackages) {
6884            // Try to find a matching persistent preferred activity.
6885            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6886                    debug, userId);
6887
6888            // If a persistent preferred activity matched, use it.
6889            if (pri != null) {
6890                return pri;
6891            }
6892
6893            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6894            // Get the list of preferred activities that handle the intent
6895            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6896            List<PreferredActivity> prefs = pir != null
6897                    ? pir.queryIntent(intent, resolvedType,
6898                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6899                            userId)
6900                    : null;
6901            if (prefs != null && prefs.size() > 0) {
6902                boolean changed = false;
6903                try {
6904                    // First figure out how good the original match set is.
6905                    // We will only allow preferred activities that came
6906                    // from the same match quality.
6907                    int match = 0;
6908
6909                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6910
6911                    final int N = query.size();
6912                    for (int j=0; j<N; j++) {
6913                        final ResolveInfo ri = query.get(j);
6914                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6915                                + ": 0x" + Integer.toHexString(match));
6916                        if (ri.match > match) {
6917                            match = ri.match;
6918                        }
6919                    }
6920
6921                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6922                            + Integer.toHexString(match));
6923
6924                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6925                    final int M = prefs.size();
6926                    for (int i=0; i<M; i++) {
6927                        final PreferredActivity pa = prefs.get(i);
6928                        if (DEBUG_PREFERRED || debug) {
6929                            Slog.v(TAG, "Checking PreferredActivity ds="
6930                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6931                                    + "\n  component=" + pa.mPref.mComponent);
6932                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6933                        }
6934                        if (pa.mPref.mMatch != match) {
6935                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6936                                    + Integer.toHexString(pa.mPref.mMatch));
6937                            continue;
6938                        }
6939                        // If it's not an "always" type preferred activity and that's what we're
6940                        // looking for, skip it.
6941                        if (always && !pa.mPref.mAlways) {
6942                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6943                            continue;
6944                        }
6945                        final ActivityInfo ai = getActivityInfo(
6946                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6947                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6948                                userId);
6949                        if (DEBUG_PREFERRED || debug) {
6950                            Slog.v(TAG, "Found preferred activity:");
6951                            if (ai != null) {
6952                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6953                            } else {
6954                                Slog.v(TAG, "  null");
6955                            }
6956                        }
6957                        if (ai == null) {
6958                            // This previously registered preferred activity
6959                            // component is no longer known.  Most likely an update
6960                            // to the app was installed and in the new version this
6961                            // component no longer exists.  Clean it up by removing
6962                            // it from the preferred activities list, and skip it.
6963                            Slog.w(TAG, "Removing dangling preferred activity: "
6964                                    + pa.mPref.mComponent);
6965                            pir.removeFilter(pa);
6966                            changed = true;
6967                            continue;
6968                        }
6969                        for (int j=0; j<N; j++) {
6970                            final ResolveInfo ri = query.get(j);
6971                            if (!ri.activityInfo.applicationInfo.packageName
6972                                    .equals(ai.applicationInfo.packageName)) {
6973                                continue;
6974                            }
6975                            if (!ri.activityInfo.name.equals(ai.name)) {
6976                                continue;
6977                            }
6978
6979                            if (removeMatches) {
6980                                pir.removeFilter(pa);
6981                                changed = true;
6982                                if (DEBUG_PREFERRED) {
6983                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6984                                }
6985                                break;
6986                            }
6987
6988                            // Okay we found a previously set preferred or last chosen app.
6989                            // If the result set is different from when this
6990                            // was created, we need to clear it and re-ask the
6991                            // user their preference, if we're looking for an "always" type entry.
6992                            if (always && !pa.mPref.sameSet(query)) {
6993                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6994                                        + intent + " type " + resolvedType);
6995                                if (DEBUG_PREFERRED) {
6996                                    Slog.v(TAG, "Removing preferred activity since set changed "
6997                                            + pa.mPref.mComponent);
6998                                }
6999                                pir.removeFilter(pa);
7000                                // Re-add the filter as a "last chosen" entry (!always)
7001                                PreferredActivity lastChosen = new PreferredActivity(
7002                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7003                                pir.addFilter(lastChosen);
7004                                changed = true;
7005                                return null;
7006                            }
7007
7008                            // Yay! Either the set matched or we're looking for the last chosen
7009                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7010                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7011                            return ri;
7012                        }
7013                    }
7014                } finally {
7015                    if (changed) {
7016                        if (DEBUG_PREFERRED) {
7017                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7018                        }
7019                        scheduleWritePackageRestrictionsLocked(userId);
7020                    }
7021                }
7022            }
7023        }
7024        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7025        return null;
7026    }
7027
7028    /*
7029     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7030     */
7031    @Override
7032    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7033            int targetUserId) {
7034        mContext.enforceCallingOrSelfPermission(
7035                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7036        List<CrossProfileIntentFilter> matches =
7037                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7038        if (matches != null) {
7039            int size = matches.size();
7040            for (int i = 0; i < size; i++) {
7041                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7042            }
7043        }
7044        if (hasWebURI(intent)) {
7045            // cross-profile app linking works only towards the parent.
7046            final int callingUid = Binder.getCallingUid();
7047            final UserInfo parent = getProfileParent(sourceUserId);
7048            synchronized(mPackages) {
7049                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7050                        false /*includeInstantApps*/);
7051                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7052                        intent, resolvedType, flags, sourceUserId, parent.id);
7053                return xpDomainInfo != null;
7054            }
7055        }
7056        return false;
7057    }
7058
7059    private UserInfo getProfileParent(int userId) {
7060        final long identity = Binder.clearCallingIdentity();
7061        try {
7062            return sUserManager.getProfileParent(userId);
7063        } finally {
7064            Binder.restoreCallingIdentity(identity);
7065        }
7066    }
7067
7068    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7069            String resolvedType, int userId) {
7070        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7071        if (resolver != null) {
7072            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7073        }
7074        return null;
7075    }
7076
7077    @Override
7078    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7079            String resolvedType, int flags, int userId) {
7080        try {
7081            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7082
7083            return new ParceledListSlice<>(
7084                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7085        } finally {
7086            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7087        }
7088    }
7089
7090    /**
7091     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7092     * instant, returns {@code null}.
7093     */
7094    private String getInstantAppPackageName(int callingUid) {
7095        synchronized (mPackages) {
7096            // If the caller is an isolated app use the owner's uid for the lookup.
7097            if (Process.isIsolated(callingUid)) {
7098                callingUid = mIsolatedOwners.get(callingUid);
7099            }
7100            final int appId = UserHandle.getAppId(callingUid);
7101            final Object obj = mSettings.getUserIdLPr(appId);
7102            if (obj instanceof PackageSetting) {
7103                final PackageSetting ps = (PackageSetting) obj;
7104                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7105                return isInstantApp ? ps.pkg.packageName : null;
7106            }
7107        }
7108        return null;
7109    }
7110
7111    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7112            String resolvedType, int flags, int userId) {
7113        return queryIntentActivitiesInternal(
7114                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
7115    }
7116
7117    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7118            String resolvedType, int flags, int filterCallingUid, int userId,
7119            boolean resolveForStart) {
7120        if (!sUserManager.exists(userId)) return Collections.emptyList();
7121        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7122        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7123                false /* requireFullPermission */, false /* checkShell */,
7124                "query intent activities");
7125        final String pkgName = intent.getPackage();
7126        ComponentName comp = intent.getComponent();
7127        if (comp == null) {
7128            if (intent.getSelector() != null) {
7129                intent = intent.getSelector();
7130                comp = intent.getComponent();
7131            }
7132        }
7133
7134        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7135                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7136        if (comp != null) {
7137            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7138            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7139            if (ai != null) {
7140                // When specifying an explicit component, we prevent the activity from being
7141                // used when either 1) the calling package is normal and the activity is within
7142                // an ephemeral application or 2) the calling package is ephemeral and the
7143                // activity is not visible to ephemeral applications.
7144                final boolean matchInstantApp =
7145                        (flags & PackageManager.MATCH_INSTANT) != 0;
7146                final boolean matchVisibleToInstantAppOnly =
7147                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7148                final boolean matchExplicitlyVisibleOnly =
7149                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7150                final boolean isCallerInstantApp =
7151                        instantAppPkgName != null;
7152                final boolean isTargetSameInstantApp =
7153                        comp.getPackageName().equals(instantAppPkgName);
7154                final boolean isTargetInstantApp =
7155                        (ai.applicationInfo.privateFlags
7156                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7157                final boolean isTargetVisibleToInstantApp =
7158                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7159                final boolean isTargetExplicitlyVisibleToInstantApp =
7160                        isTargetVisibleToInstantApp
7161                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7162                final boolean isTargetHiddenFromInstantApp =
7163                        !isTargetVisibleToInstantApp
7164                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7165                final boolean blockResolution =
7166                        !isTargetSameInstantApp
7167                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7168                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7169                                        && isTargetHiddenFromInstantApp));
7170                if (!blockResolution) {
7171                    final ResolveInfo ri = new ResolveInfo();
7172                    ri.activityInfo = ai;
7173                    list.add(ri);
7174                }
7175            }
7176            return applyPostResolutionFilter(list, instantAppPkgName);
7177        }
7178
7179        // reader
7180        boolean sortResult = false;
7181        boolean addEphemeral = false;
7182        List<ResolveInfo> result;
7183        final boolean ephemeralDisabled = isEphemeralDisabled();
7184        synchronized (mPackages) {
7185            if (pkgName == null) {
7186                List<CrossProfileIntentFilter> matchingFilters =
7187                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7188                // Check for results that need to skip the current profile.
7189                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7190                        resolvedType, flags, userId);
7191                if (xpResolveInfo != null) {
7192                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7193                    xpResult.add(xpResolveInfo);
7194                    return applyPostResolutionFilter(
7195                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
7196                }
7197
7198                // Check for results in the current profile.
7199                result = filterIfNotSystemUser(mActivities.queryIntent(
7200                        intent, resolvedType, flags, userId), userId);
7201                addEphemeral = !ephemeralDisabled
7202                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7203                // Check for cross profile results.
7204                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7205                xpResolveInfo = queryCrossProfileIntents(
7206                        matchingFilters, intent, resolvedType, flags, userId,
7207                        hasNonNegativePriorityResult);
7208                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7209                    boolean isVisibleToUser = filterIfNotSystemUser(
7210                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7211                    if (isVisibleToUser) {
7212                        result.add(xpResolveInfo);
7213                        sortResult = true;
7214                    }
7215                }
7216                if (hasWebURI(intent)) {
7217                    CrossProfileDomainInfo xpDomainInfo = null;
7218                    final UserInfo parent = getProfileParent(userId);
7219                    if (parent != null) {
7220                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7221                                flags, userId, parent.id);
7222                    }
7223                    if (xpDomainInfo != null) {
7224                        if (xpResolveInfo != null) {
7225                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7226                            // in the result.
7227                            result.remove(xpResolveInfo);
7228                        }
7229                        if (result.size() == 0 && !addEphemeral) {
7230                            // No result in current profile, but found candidate in parent user.
7231                            // And we are not going to add emphemeral app, so we can return the
7232                            // result straight away.
7233                            result.add(xpDomainInfo.resolveInfo);
7234                            return applyPostResolutionFilter(result, instantAppPkgName);
7235                        }
7236                    } else if (result.size() <= 1 && !addEphemeral) {
7237                        // No result in parent user and <= 1 result in current profile, and we
7238                        // are not going to add emphemeral app, so we can return the result without
7239                        // further processing.
7240                        return applyPostResolutionFilter(result, instantAppPkgName);
7241                    }
7242                    // We have more than one candidate (combining results from current and parent
7243                    // profile), so we need filtering and sorting.
7244                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7245                            intent, flags, result, xpDomainInfo, userId);
7246                    sortResult = true;
7247                }
7248            } else {
7249                final PackageParser.Package pkg = mPackages.get(pkgName);
7250                result = null;
7251                if (pkg != null) {
7252                    result = filterIfNotSystemUser(
7253                            mActivities.queryIntentForPackage(
7254                                    intent, resolvedType, flags, pkg.activities, userId),
7255                            userId);
7256                }
7257                if (result == null || result.size() == 0) {
7258                    // the caller wants to resolve for a particular package; however, there
7259                    // were no installed results, so, try to find an ephemeral result
7260                    addEphemeral = !ephemeralDisabled
7261                            && isInstantAppAllowed(
7262                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7263                    if (result == null) {
7264                        result = new ArrayList<>();
7265                    }
7266                }
7267            }
7268        }
7269        if (addEphemeral) {
7270            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7271        }
7272        if (sortResult) {
7273            Collections.sort(result, mResolvePrioritySorter);
7274        }
7275        return applyPostResolutionFilter(result, instantAppPkgName);
7276    }
7277
7278    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7279            String resolvedType, int flags, int userId) {
7280        // first, check to see if we've got an instant app already installed
7281        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7282        ResolveInfo localInstantApp = null;
7283        boolean blockResolution = false;
7284        if (!alreadyResolvedLocally) {
7285            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7286                    flags
7287                        | PackageManager.GET_RESOLVED_FILTER
7288                        | PackageManager.MATCH_INSTANT
7289                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7290                    userId);
7291            for (int i = instantApps.size() - 1; i >= 0; --i) {
7292                final ResolveInfo info = instantApps.get(i);
7293                final String packageName = info.activityInfo.packageName;
7294                final PackageSetting ps = mSettings.mPackages.get(packageName);
7295                if (ps.getInstantApp(userId)) {
7296                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7297                    final int status = (int)(packedStatus >> 32);
7298                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7299                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7300                        // there's a local instant application installed, but, the user has
7301                        // chosen to never use it; skip resolution and don't acknowledge
7302                        // an instant application is even available
7303                        if (DEBUG_EPHEMERAL) {
7304                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7305                        }
7306                        blockResolution = true;
7307                        break;
7308                    } else {
7309                        // we have a locally installed instant application; skip resolution
7310                        // but acknowledge there's an instant application available
7311                        if (DEBUG_EPHEMERAL) {
7312                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7313                        }
7314                        localInstantApp = info;
7315                        break;
7316                    }
7317                }
7318            }
7319        }
7320        // no app installed, let's see if one's available
7321        AuxiliaryResolveInfo auxiliaryResponse = null;
7322        if (!blockResolution) {
7323            if (localInstantApp == null) {
7324                // we don't have an instant app locally, resolve externally
7325                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7326                final InstantAppRequest requestObject = new InstantAppRequest(
7327                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7328                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7329                auxiliaryResponse =
7330                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7331                                mContext, mInstantAppResolverConnection, requestObject);
7332                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7333            } else {
7334                // we have an instant application locally, but, we can't admit that since
7335                // callers shouldn't be able to determine prior browsing. create a dummy
7336                // auxiliary response so the downstream code behaves as if there's an
7337                // instant application available externally. when it comes time to start
7338                // the instant application, we'll do the right thing.
7339                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7340                auxiliaryResponse = new AuxiliaryResolveInfo(
7341                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7342            }
7343        }
7344        if (auxiliaryResponse != null) {
7345            if (DEBUG_EPHEMERAL) {
7346                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7347            }
7348            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7349            final PackageSetting ps =
7350                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7351            if (ps != null) {
7352                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7353                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7354                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7355                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7356                // make sure this resolver is the default
7357                ephemeralInstaller.isDefault = true;
7358                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7359                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7360                // add a non-generic filter
7361                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7362                ephemeralInstaller.filter.addDataPath(
7363                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7364                ephemeralInstaller.isInstantAppAvailable = true;
7365                result.add(ephemeralInstaller);
7366            }
7367        }
7368        return result;
7369    }
7370
7371    private static class CrossProfileDomainInfo {
7372        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7373        ResolveInfo resolveInfo;
7374        /* Best domain verification status of the activities found in the other profile */
7375        int bestDomainVerificationStatus;
7376    }
7377
7378    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7379            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7380        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7381                sourceUserId)) {
7382            return null;
7383        }
7384        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7385                resolvedType, flags, parentUserId);
7386
7387        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7388            return null;
7389        }
7390        CrossProfileDomainInfo result = null;
7391        int size = resultTargetUser.size();
7392        for (int i = 0; i < size; i++) {
7393            ResolveInfo riTargetUser = resultTargetUser.get(i);
7394            // Intent filter verification is only for filters that specify a host. So don't return
7395            // those that handle all web uris.
7396            if (riTargetUser.handleAllWebDataURI) {
7397                continue;
7398            }
7399            String packageName = riTargetUser.activityInfo.packageName;
7400            PackageSetting ps = mSettings.mPackages.get(packageName);
7401            if (ps == null) {
7402                continue;
7403            }
7404            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7405            int status = (int)(verificationState >> 32);
7406            if (result == null) {
7407                result = new CrossProfileDomainInfo();
7408                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7409                        sourceUserId, parentUserId);
7410                result.bestDomainVerificationStatus = status;
7411            } else {
7412                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7413                        result.bestDomainVerificationStatus);
7414            }
7415        }
7416        // Don't consider matches with status NEVER across profiles.
7417        if (result != null && result.bestDomainVerificationStatus
7418                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7419            return null;
7420        }
7421        return result;
7422    }
7423
7424    /**
7425     * Verification statuses are ordered from the worse to the best, except for
7426     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7427     */
7428    private int bestDomainVerificationStatus(int status1, int status2) {
7429        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7430            return status2;
7431        }
7432        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7433            return status1;
7434        }
7435        return (int) MathUtils.max(status1, status2);
7436    }
7437
7438    private boolean isUserEnabled(int userId) {
7439        long callingId = Binder.clearCallingIdentity();
7440        try {
7441            UserInfo userInfo = sUserManager.getUserInfo(userId);
7442            return userInfo != null && userInfo.isEnabled();
7443        } finally {
7444            Binder.restoreCallingIdentity(callingId);
7445        }
7446    }
7447
7448    /**
7449     * Filter out activities with systemUserOnly flag set, when current user is not System.
7450     *
7451     * @return filtered list
7452     */
7453    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7454        if (userId == UserHandle.USER_SYSTEM) {
7455            return resolveInfos;
7456        }
7457        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7458            ResolveInfo info = resolveInfos.get(i);
7459            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7460                resolveInfos.remove(i);
7461            }
7462        }
7463        return resolveInfos;
7464    }
7465
7466    /**
7467     * Filters out ephemeral activities.
7468     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7469     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7470     *
7471     * @param resolveInfos The pre-filtered list of resolved activities
7472     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7473     *          is performed.
7474     * @return A filtered list of resolved activities.
7475     */
7476    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7477            String ephemeralPkgName) {
7478        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7479            final ResolveInfo info = resolveInfos.get(i);
7480            // TODO: When adding on-demand split support for non-instant apps, remove this check
7481            // and always apply post filtering
7482            // allow activities that are defined in the provided package
7483            if (info.activityInfo.splitName != null
7484                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7485                            info.activityInfo.splitName)) {
7486                // requested activity is defined in a split that hasn't been installed yet.
7487                // add the installer to the resolve list
7488                if (DEBUG_INSTALL) {
7489                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7490                }
7491                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7492                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7493                        info.activityInfo.packageName, info.activityInfo.splitName,
7494                        info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7495                // make sure this resolver is the default
7496                installerInfo.isDefault = true;
7497                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7498                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7499                // add a non-generic filter
7500                installerInfo.filter = new IntentFilter();
7501                // load resources from the correct package
7502                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7503                resolveInfos.set(i, installerInfo);
7504                continue;
7505            }
7506            // caller is a full app, don't need to apply any other filtering
7507            if (ephemeralPkgName == null) {
7508                continue;
7509            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7510                // caller is same app; don't need to apply any other filtering
7511                continue;
7512            }
7513            // allow activities that have been explicitly exposed to ephemeral apps
7514            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7515            if (!isEphemeralApp
7516                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7517                continue;
7518            }
7519            resolveInfos.remove(i);
7520        }
7521        return resolveInfos;
7522    }
7523
7524    /**
7525     * @param resolveInfos list of resolve infos in descending priority order
7526     * @return if the list contains a resolve info with non-negative priority
7527     */
7528    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7529        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7530    }
7531
7532    private static boolean hasWebURI(Intent intent) {
7533        if (intent.getData() == null) {
7534            return false;
7535        }
7536        final String scheme = intent.getScheme();
7537        if (TextUtils.isEmpty(scheme)) {
7538            return false;
7539        }
7540        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7541    }
7542
7543    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7544            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7545            int userId) {
7546        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7547
7548        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7549            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7550                    candidates.size());
7551        }
7552
7553        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7554        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7555        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7556        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7557        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7558        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7559
7560        synchronized (mPackages) {
7561            final int count = candidates.size();
7562            // First, try to use linked apps. Partition the candidates into four lists:
7563            // one for the final results, one for the "do not use ever", one for "undefined status"
7564            // and finally one for "browser app type".
7565            for (int n=0; n<count; n++) {
7566                ResolveInfo info = candidates.get(n);
7567                String packageName = info.activityInfo.packageName;
7568                PackageSetting ps = mSettings.mPackages.get(packageName);
7569                if (ps != null) {
7570                    // Add to the special match all list (Browser use case)
7571                    if (info.handleAllWebDataURI) {
7572                        matchAllList.add(info);
7573                        continue;
7574                    }
7575                    // Try to get the status from User settings first
7576                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7577                    int status = (int)(packedStatus >> 32);
7578                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7579                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7580                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7581                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7582                                    + " : linkgen=" + linkGeneration);
7583                        }
7584                        // Use link-enabled generation as preferredOrder, i.e.
7585                        // prefer newly-enabled over earlier-enabled.
7586                        info.preferredOrder = linkGeneration;
7587                        alwaysList.add(info);
7588                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7589                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7590                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7591                        }
7592                        neverList.add(info);
7593                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7594                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7595                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7596                        }
7597                        alwaysAskList.add(info);
7598                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7599                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7600                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7601                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7602                        }
7603                        undefinedList.add(info);
7604                    }
7605                }
7606            }
7607
7608            // We'll want to include browser possibilities in a few cases
7609            boolean includeBrowser = false;
7610
7611            // First try to add the "always" resolution(s) for the current user, if any
7612            if (alwaysList.size() > 0) {
7613                result.addAll(alwaysList);
7614            } else {
7615                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7616                result.addAll(undefinedList);
7617                // Maybe add one for the other profile.
7618                if (xpDomainInfo != null && (
7619                        xpDomainInfo.bestDomainVerificationStatus
7620                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7621                    result.add(xpDomainInfo.resolveInfo);
7622                }
7623                includeBrowser = true;
7624            }
7625
7626            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7627            // If there were 'always' entries their preferred order has been set, so we also
7628            // back that off to make the alternatives equivalent
7629            if (alwaysAskList.size() > 0) {
7630                for (ResolveInfo i : result) {
7631                    i.preferredOrder = 0;
7632                }
7633                result.addAll(alwaysAskList);
7634                includeBrowser = true;
7635            }
7636
7637            if (includeBrowser) {
7638                // Also add browsers (all of them or only the default one)
7639                if (DEBUG_DOMAIN_VERIFICATION) {
7640                    Slog.v(TAG, "   ...including browsers in candidate set");
7641                }
7642                if ((matchFlags & MATCH_ALL) != 0) {
7643                    result.addAll(matchAllList);
7644                } else {
7645                    // Browser/generic handling case.  If there's a default browser, go straight
7646                    // to that (but only if there is no other higher-priority match).
7647                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7648                    int maxMatchPrio = 0;
7649                    ResolveInfo defaultBrowserMatch = null;
7650                    final int numCandidates = matchAllList.size();
7651                    for (int n = 0; n < numCandidates; n++) {
7652                        ResolveInfo info = matchAllList.get(n);
7653                        // track the highest overall match priority...
7654                        if (info.priority > maxMatchPrio) {
7655                            maxMatchPrio = info.priority;
7656                        }
7657                        // ...and the highest-priority default browser match
7658                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7659                            if (defaultBrowserMatch == null
7660                                    || (defaultBrowserMatch.priority < info.priority)) {
7661                                if (debug) {
7662                                    Slog.v(TAG, "Considering default browser match " + info);
7663                                }
7664                                defaultBrowserMatch = info;
7665                            }
7666                        }
7667                    }
7668                    if (defaultBrowserMatch != null
7669                            && defaultBrowserMatch.priority >= maxMatchPrio
7670                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7671                    {
7672                        if (debug) {
7673                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7674                        }
7675                        result.add(defaultBrowserMatch);
7676                    } else {
7677                        result.addAll(matchAllList);
7678                    }
7679                }
7680
7681                // If there is nothing selected, add all candidates and remove the ones that the user
7682                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7683                if (result.size() == 0) {
7684                    result.addAll(candidates);
7685                    result.removeAll(neverList);
7686                }
7687            }
7688        }
7689        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7690            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7691                    result.size());
7692            for (ResolveInfo info : result) {
7693                Slog.v(TAG, "  + " + info.activityInfo);
7694            }
7695        }
7696        return result;
7697    }
7698
7699    // Returns a packed value as a long:
7700    //
7701    // high 'int'-sized word: link status: undefined/ask/never/always.
7702    // low 'int'-sized word: relative priority among 'always' results.
7703    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7704        long result = ps.getDomainVerificationStatusForUser(userId);
7705        // if none available, get the master status
7706        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7707            if (ps.getIntentFilterVerificationInfo() != null) {
7708                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7709            }
7710        }
7711        return result;
7712    }
7713
7714    private ResolveInfo querySkipCurrentProfileIntents(
7715            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7716            int flags, int sourceUserId) {
7717        if (matchingFilters != null) {
7718            int size = matchingFilters.size();
7719            for (int i = 0; i < size; i ++) {
7720                CrossProfileIntentFilter filter = matchingFilters.get(i);
7721                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7722                    // Checking if there are activities in the target user that can handle the
7723                    // intent.
7724                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7725                            resolvedType, flags, sourceUserId);
7726                    if (resolveInfo != null) {
7727                        return resolveInfo;
7728                    }
7729                }
7730            }
7731        }
7732        return null;
7733    }
7734
7735    // Return matching ResolveInfo in target user if any.
7736    private ResolveInfo queryCrossProfileIntents(
7737            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7738            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7739        if (matchingFilters != null) {
7740            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7741            // match the same intent. For performance reasons, it is better not to
7742            // run queryIntent twice for the same userId
7743            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7744            int size = matchingFilters.size();
7745            for (int i = 0; i < size; i++) {
7746                CrossProfileIntentFilter filter = matchingFilters.get(i);
7747                int targetUserId = filter.getTargetUserId();
7748                boolean skipCurrentProfile =
7749                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7750                boolean skipCurrentProfileIfNoMatchFound =
7751                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7752                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7753                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7754                    // Checking if there are activities in the target user that can handle the
7755                    // intent.
7756                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7757                            resolvedType, flags, sourceUserId);
7758                    if (resolveInfo != null) return resolveInfo;
7759                    alreadyTriedUserIds.put(targetUserId, true);
7760                }
7761            }
7762        }
7763        return null;
7764    }
7765
7766    /**
7767     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7768     * will forward the intent to the filter's target user.
7769     * Otherwise, returns null.
7770     */
7771    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7772            String resolvedType, int flags, int sourceUserId) {
7773        int targetUserId = filter.getTargetUserId();
7774        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7775                resolvedType, flags, targetUserId);
7776        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7777            // If all the matches in the target profile are suspended, return null.
7778            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7779                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7780                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7781                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7782                            targetUserId);
7783                }
7784            }
7785        }
7786        return null;
7787    }
7788
7789    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7790            int sourceUserId, int targetUserId) {
7791        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7792        long ident = Binder.clearCallingIdentity();
7793        boolean targetIsProfile;
7794        try {
7795            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7796        } finally {
7797            Binder.restoreCallingIdentity(ident);
7798        }
7799        String className;
7800        if (targetIsProfile) {
7801            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7802        } else {
7803            className = FORWARD_INTENT_TO_PARENT;
7804        }
7805        ComponentName forwardingActivityComponentName = new ComponentName(
7806                mAndroidApplication.packageName, className);
7807        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7808                sourceUserId);
7809        if (!targetIsProfile) {
7810            forwardingActivityInfo.showUserIcon = targetUserId;
7811            forwardingResolveInfo.noResourceId = true;
7812        }
7813        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7814        forwardingResolveInfo.priority = 0;
7815        forwardingResolveInfo.preferredOrder = 0;
7816        forwardingResolveInfo.match = 0;
7817        forwardingResolveInfo.isDefault = true;
7818        forwardingResolveInfo.filter = filter;
7819        forwardingResolveInfo.targetUserId = targetUserId;
7820        return forwardingResolveInfo;
7821    }
7822
7823    @Override
7824    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7825            Intent[] specifics, String[] specificTypes, Intent intent,
7826            String resolvedType, int flags, int userId) {
7827        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7828                specificTypes, intent, resolvedType, flags, userId));
7829    }
7830
7831    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7832            Intent[] specifics, String[] specificTypes, Intent intent,
7833            String resolvedType, int flags, int userId) {
7834        if (!sUserManager.exists(userId)) return Collections.emptyList();
7835        final int callingUid = Binder.getCallingUid();
7836        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7837                false /*includeInstantApps*/);
7838        enforceCrossUserPermission(callingUid, userId,
7839                false /*requireFullPermission*/, false /*checkShell*/,
7840                "query intent activity options");
7841        final String resultsAction = intent.getAction();
7842
7843        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7844                | PackageManager.GET_RESOLVED_FILTER, userId);
7845
7846        if (DEBUG_INTENT_MATCHING) {
7847            Log.v(TAG, "Query " + intent + ": " + results);
7848        }
7849
7850        int specificsPos = 0;
7851        int N;
7852
7853        // todo: note that the algorithm used here is O(N^2).  This
7854        // isn't a problem in our current environment, but if we start running
7855        // into situations where we have more than 5 or 10 matches then this
7856        // should probably be changed to something smarter...
7857
7858        // First we go through and resolve each of the specific items
7859        // that were supplied, taking care of removing any corresponding
7860        // duplicate items in the generic resolve list.
7861        if (specifics != null) {
7862            for (int i=0; i<specifics.length; i++) {
7863                final Intent sintent = specifics[i];
7864                if (sintent == null) {
7865                    continue;
7866                }
7867
7868                if (DEBUG_INTENT_MATCHING) {
7869                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7870                }
7871
7872                String action = sintent.getAction();
7873                if (resultsAction != null && resultsAction.equals(action)) {
7874                    // If this action was explicitly requested, then don't
7875                    // remove things that have it.
7876                    action = null;
7877                }
7878
7879                ResolveInfo ri = null;
7880                ActivityInfo ai = null;
7881
7882                ComponentName comp = sintent.getComponent();
7883                if (comp == null) {
7884                    ri = resolveIntent(
7885                        sintent,
7886                        specificTypes != null ? specificTypes[i] : null,
7887                            flags, userId);
7888                    if (ri == null) {
7889                        continue;
7890                    }
7891                    if (ri == mResolveInfo) {
7892                        // ACK!  Must do something better with this.
7893                    }
7894                    ai = ri.activityInfo;
7895                    comp = new ComponentName(ai.applicationInfo.packageName,
7896                            ai.name);
7897                } else {
7898                    ai = getActivityInfo(comp, flags, userId);
7899                    if (ai == null) {
7900                        continue;
7901                    }
7902                }
7903
7904                // Look for any generic query activities that are duplicates
7905                // of this specific one, and remove them from the results.
7906                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7907                N = results.size();
7908                int j;
7909                for (j=specificsPos; j<N; j++) {
7910                    ResolveInfo sri = results.get(j);
7911                    if ((sri.activityInfo.name.equals(comp.getClassName())
7912                            && sri.activityInfo.applicationInfo.packageName.equals(
7913                                    comp.getPackageName()))
7914                        || (action != null && sri.filter.matchAction(action))) {
7915                        results.remove(j);
7916                        if (DEBUG_INTENT_MATCHING) Log.v(
7917                            TAG, "Removing duplicate item from " + j
7918                            + " due to specific " + specificsPos);
7919                        if (ri == null) {
7920                            ri = sri;
7921                        }
7922                        j--;
7923                        N--;
7924                    }
7925                }
7926
7927                // Add this specific item to its proper place.
7928                if (ri == null) {
7929                    ri = new ResolveInfo();
7930                    ri.activityInfo = ai;
7931                }
7932                results.add(specificsPos, ri);
7933                ri.specificIndex = i;
7934                specificsPos++;
7935            }
7936        }
7937
7938        // Now we go through the remaining generic results and remove any
7939        // duplicate actions that are found here.
7940        N = results.size();
7941        for (int i=specificsPos; i<N-1; i++) {
7942            final ResolveInfo rii = results.get(i);
7943            if (rii.filter == null) {
7944                continue;
7945            }
7946
7947            // Iterate over all of the actions of this result's intent
7948            // filter...  typically this should be just one.
7949            final Iterator<String> it = rii.filter.actionsIterator();
7950            if (it == null) {
7951                continue;
7952            }
7953            while (it.hasNext()) {
7954                final String action = it.next();
7955                if (resultsAction != null && resultsAction.equals(action)) {
7956                    // If this action was explicitly requested, then don't
7957                    // remove things that have it.
7958                    continue;
7959                }
7960                for (int j=i+1; j<N; j++) {
7961                    final ResolveInfo rij = results.get(j);
7962                    if (rij.filter != null && rij.filter.hasAction(action)) {
7963                        results.remove(j);
7964                        if (DEBUG_INTENT_MATCHING) Log.v(
7965                            TAG, "Removing duplicate item from " + j
7966                            + " due to action " + action + " at " + i);
7967                        j--;
7968                        N--;
7969                    }
7970                }
7971            }
7972
7973            // If the caller didn't request filter information, drop it now
7974            // so we don't have to marshall/unmarshall it.
7975            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7976                rii.filter = null;
7977            }
7978        }
7979
7980        // Filter out the caller activity if so requested.
7981        if (caller != null) {
7982            N = results.size();
7983            for (int i=0; i<N; i++) {
7984                ActivityInfo ainfo = results.get(i).activityInfo;
7985                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7986                        && caller.getClassName().equals(ainfo.name)) {
7987                    results.remove(i);
7988                    break;
7989                }
7990            }
7991        }
7992
7993        // If the caller didn't request filter information,
7994        // drop them now so we don't have to
7995        // marshall/unmarshall it.
7996        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7997            N = results.size();
7998            for (int i=0; i<N; i++) {
7999                results.get(i).filter = null;
8000            }
8001        }
8002
8003        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8004        return results;
8005    }
8006
8007    @Override
8008    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8009            String resolvedType, int flags, int userId) {
8010        return new ParceledListSlice<>(
8011                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
8012    }
8013
8014    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8015            String resolvedType, int flags, int userId) {
8016        if (!sUserManager.exists(userId)) return Collections.emptyList();
8017        final int callingUid = Binder.getCallingUid();
8018        enforceCrossUserPermission(callingUid, userId,
8019                false /*requireFullPermission*/, false /*checkShell*/,
8020                "query intent receivers");
8021        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8022        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8023                false /*includeInstantApps*/);
8024        ComponentName comp = intent.getComponent();
8025        if (comp == null) {
8026            if (intent.getSelector() != null) {
8027                intent = intent.getSelector();
8028                comp = intent.getComponent();
8029            }
8030        }
8031        if (comp != null) {
8032            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8033            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8034            if (ai != null) {
8035                // When specifying an explicit component, we prevent the activity from being
8036                // used when either 1) the calling package is normal and the activity is within
8037                // an instant application or 2) the calling package is ephemeral and the
8038                // activity is not visible to instant applications.
8039                final boolean matchInstantApp =
8040                        (flags & PackageManager.MATCH_INSTANT) != 0;
8041                final boolean matchVisibleToInstantAppOnly =
8042                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8043                final boolean matchExplicitlyVisibleOnly =
8044                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8045                final boolean isCallerInstantApp =
8046                        instantAppPkgName != null;
8047                final boolean isTargetSameInstantApp =
8048                        comp.getPackageName().equals(instantAppPkgName);
8049                final boolean isTargetInstantApp =
8050                        (ai.applicationInfo.privateFlags
8051                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8052                final boolean isTargetVisibleToInstantApp =
8053                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8054                final boolean isTargetExplicitlyVisibleToInstantApp =
8055                        isTargetVisibleToInstantApp
8056                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8057                final boolean isTargetHiddenFromInstantApp =
8058                        !isTargetVisibleToInstantApp
8059                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8060                final boolean blockResolution =
8061                        !isTargetSameInstantApp
8062                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8063                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8064                                        && isTargetHiddenFromInstantApp));
8065                if (!blockResolution) {
8066                    ResolveInfo ri = new ResolveInfo();
8067                    ri.activityInfo = ai;
8068                    list.add(ri);
8069                }
8070            }
8071            return applyPostResolutionFilter(list, instantAppPkgName);
8072        }
8073
8074        // reader
8075        synchronized (mPackages) {
8076            String pkgName = intent.getPackage();
8077            if (pkgName == null) {
8078                final List<ResolveInfo> result =
8079                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8080                return applyPostResolutionFilter(result, instantAppPkgName);
8081            }
8082            final PackageParser.Package pkg = mPackages.get(pkgName);
8083            if (pkg != null) {
8084                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8085                        intent, resolvedType, flags, pkg.receivers, userId);
8086                return applyPostResolutionFilter(result, instantAppPkgName);
8087            }
8088            return Collections.emptyList();
8089        }
8090    }
8091
8092    @Override
8093    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8094        final int callingUid = Binder.getCallingUid();
8095        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8096    }
8097
8098    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8099            int userId, int callingUid) {
8100        if (!sUserManager.exists(userId)) return null;
8101        flags = updateFlagsForResolve(
8102                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8103        List<ResolveInfo> query = queryIntentServicesInternal(
8104                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8105        if (query != null) {
8106            if (query.size() >= 1) {
8107                // If there is more than one service with the same priority,
8108                // just arbitrarily pick the first one.
8109                return query.get(0);
8110            }
8111        }
8112        return null;
8113    }
8114
8115    @Override
8116    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8117            String resolvedType, int flags, int userId) {
8118        final int callingUid = Binder.getCallingUid();
8119        return new ParceledListSlice<>(queryIntentServicesInternal(
8120                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8121    }
8122
8123    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8124            String resolvedType, int flags, int userId, int callingUid,
8125            boolean includeInstantApps) {
8126        if (!sUserManager.exists(userId)) return Collections.emptyList();
8127        enforceCrossUserPermission(callingUid, userId,
8128                false /*requireFullPermission*/, false /*checkShell*/,
8129                "query intent receivers");
8130        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8131        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8132        ComponentName comp = intent.getComponent();
8133        if (comp == null) {
8134            if (intent.getSelector() != null) {
8135                intent = intent.getSelector();
8136                comp = intent.getComponent();
8137            }
8138        }
8139        if (comp != null) {
8140            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8141            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8142            if (si != null) {
8143                // When specifying an explicit component, we prevent the service from being
8144                // used when either 1) the service is in an instant application and the
8145                // caller is not the same instant application or 2) the calling package is
8146                // ephemeral and the activity is not visible to ephemeral applications.
8147                final boolean matchInstantApp =
8148                        (flags & PackageManager.MATCH_INSTANT) != 0;
8149                final boolean matchVisibleToInstantAppOnly =
8150                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8151                final boolean isCallerInstantApp =
8152                        instantAppPkgName != null;
8153                final boolean isTargetSameInstantApp =
8154                        comp.getPackageName().equals(instantAppPkgName);
8155                final boolean isTargetInstantApp =
8156                        (si.applicationInfo.privateFlags
8157                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8158                final boolean isTargetHiddenFromInstantApp =
8159                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8160                final boolean blockResolution =
8161                        !isTargetSameInstantApp
8162                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8163                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8164                                        && isTargetHiddenFromInstantApp));
8165                if (!blockResolution) {
8166                    final ResolveInfo ri = new ResolveInfo();
8167                    ri.serviceInfo = si;
8168                    list.add(ri);
8169                }
8170            }
8171            return list;
8172        }
8173
8174        // reader
8175        synchronized (mPackages) {
8176            String pkgName = intent.getPackage();
8177            if (pkgName == null) {
8178                return applyPostServiceResolutionFilter(
8179                        mServices.queryIntent(intent, resolvedType, flags, userId),
8180                        instantAppPkgName);
8181            }
8182            final PackageParser.Package pkg = mPackages.get(pkgName);
8183            if (pkg != null) {
8184                return applyPostServiceResolutionFilter(
8185                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8186                                userId),
8187                        instantAppPkgName);
8188            }
8189            return Collections.emptyList();
8190        }
8191    }
8192
8193    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8194            String instantAppPkgName) {
8195        // TODO: When adding on-demand split support for non-instant apps, remove this check
8196        // and always apply post filtering
8197        if (instantAppPkgName == null) {
8198            return resolveInfos;
8199        }
8200        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8201            final ResolveInfo info = resolveInfos.get(i);
8202            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8203            // allow services that are defined in the provided package
8204            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8205                if (info.serviceInfo.splitName != null
8206                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8207                                info.serviceInfo.splitName)) {
8208                    // requested service is defined in a split that hasn't been installed yet.
8209                    // add the installer to the resolve list
8210                    if (DEBUG_EPHEMERAL) {
8211                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8212                    }
8213                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8214                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8215                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8216                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
8217                    // make sure this resolver is the default
8218                    installerInfo.isDefault = true;
8219                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8220                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8221                    // add a non-generic filter
8222                    installerInfo.filter = new IntentFilter();
8223                    // load resources from the correct package
8224                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8225                    resolveInfos.set(i, installerInfo);
8226                }
8227                continue;
8228            }
8229            // allow services that have been explicitly exposed to ephemeral apps
8230            if (!isEphemeralApp
8231                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8232                continue;
8233            }
8234            resolveInfos.remove(i);
8235        }
8236        return resolveInfos;
8237    }
8238
8239    @Override
8240    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8241            String resolvedType, int flags, int userId) {
8242        return new ParceledListSlice<>(
8243                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8244    }
8245
8246    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8247            Intent intent, String resolvedType, int flags, int userId) {
8248        if (!sUserManager.exists(userId)) return Collections.emptyList();
8249        final int callingUid = Binder.getCallingUid();
8250        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8251        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8252                false /*includeInstantApps*/);
8253        ComponentName comp = intent.getComponent();
8254        if (comp == null) {
8255            if (intent.getSelector() != null) {
8256                intent = intent.getSelector();
8257                comp = intent.getComponent();
8258            }
8259        }
8260        if (comp != null) {
8261            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8262            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8263            if (pi != null) {
8264                // When specifying an explicit component, we prevent the provider from being
8265                // used when either 1) the provider is in an instant application and the
8266                // caller is not the same instant application or 2) the calling package is an
8267                // instant application and the provider is not visible to instant applications.
8268                final boolean matchInstantApp =
8269                        (flags & PackageManager.MATCH_INSTANT) != 0;
8270                final boolean matchVisibleToInstantAppOnly =
8271                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8272                final boolean isCallerInstantApp =
8273                        instantAppPkgName != null;
8274                final boolean isTargetSameInstantApp =
8275                        comp.getPackageName().equals(instantAppPkgName);
8276                final boolean isTargetInstantApp =
8277                        (pi.applicationInfo.privateFlags
8278                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8279                final boolean isTargetHiddenFromInstantApp =
8280                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8281                final boolean blockResolution =
8282                        !isTargetSameInstantApp
8283                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8284                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8285                                        && isTargetHiddenFromInstantApp));
8286                if (!blockResolution) {
8287                    final ResolveInfo ri = new ResolveInfo();
8288                    ri.providerInfo = pi;
8289                    list.add(ri);
8290                }
8291            }
8292            return list;
8293        }
8294
8295        // reader
8296        synchronized (mPackages) {
8297            String pkgName = intent.getPackage();
8298            if (pkgName == null) {
8299                return applyPostContentProviderResolutionFilter(
8300                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8301                        instantAppPkgName);
8302            }
8303            final PackageParser.Package pkg = mPackages.get(pkgName);
8304            if (pkg != null) {
8305                return applyPostContentProviderResolutionFilter(
8306                        mProviders.queryIntentForPackage(
8307                        intent, resolvedType, flags, pkg.providers, userId),
8308                        instantAppPkgName);
8309            }
8310            return Collections.emptyList();
8311        }
8312    }
8313
8314    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8315            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8316        // TODO: When adding on-demand split support for non-instant applications, remove
8317        // this check and always apply post filtering
8318        if (instantAppPkgName == null) {
8319            return resolveInfos;
8320        }
8321        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8322            final ResolveInfo info = resolveInfos.get(i);
8323            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8324            // allow providers that are defined in the provided package
8325            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8326                if (info.providerInfo.splitName != null
8327                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8328                                info.providerInfo.splitName)) {
8329                    // requested provider is defined in a split that hasn't been installed yet.
8330                    // add the installer to the resolve list
8331                    if (DEBUG_EPHEMERAL) {
8332                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8333                    }
8334                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8335                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8336                            info.providerInfo.packageName, info.providerInfo.splitName,
8337                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8338                    // make sure this resolver is the default
8339                    installerInfo.isDefault = true;
8340                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8341                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8342                    // add a non-generic filter
8343                    installerInfo.filter = new IntentFilter();
8344                    // load resources from the correct package
8345                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8346                    resolveInfos.set(i, installerInfo);
8347                }
8348                continue;
8349            }
8350            // allow providers that have been explicitly exposed to instant applications
8351            if (!isEphemeralApp
8352                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8353                continue;
8354            }
8355            resolveInfos.remove(i);
8356        }
8357        return resolveInfos;
8358    }
8359
8360    @Override
8361    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8362        final int callingUid = Binder.getCallingUid();
8363        if (getInstantAppPackageName(callingUid) != null) {
8364            return ParceledListSlice.emptyList();
8365        }
8366        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8367        flags = updateFlagsForPackage(flags, userId, null);
8368        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8369        enforceCrossUserPermission(callingUid, userId,
8370                true /* requireFullPermission */, false /* checkShell */,
8371                "get installed packages");
8372
8373        // writer
8374        synchronized (mPackages) {
8375            ArrayList<PackageInfo> list;
8376            if (listUninstalled) {
8377                list = new ArrayList<>(mSettings.mPackages.size());
8378                for (PackageSetting ps : mSettings.mPackages.values()) {
8379                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8380                        continue;
8381                    }
8382                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8383                        return null;
8384                    }
8385                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8386                    if (pi != null) {
8387                        list.add(pi);
8388                    }
8389                }
8390            } else {
8391                list = new ArrayList<>(mPackages.size());
8392                for (PackageParser.Package p : mPackages.values()) {
8393                    final PackageSetting ps = (PackageSetting) p.mExtras;
8394                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8395                        continue;
8396                    }
8397                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8398                        return null;
8399                    }
8400                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8401                            p.mExtras, flags, userId);
8402                    if (pi != null) {
8403                        list.add(pi);
8404                    }
8405                }
8406            }
8407
8408            return new ParceledListSlice<>(list);
8409        }
8410    }
8411
8412    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8413            String[] permissions, boolean[] tmp, int flags, int userId) {
8414        int numMatch = 0;
8415        final PermissionsState permissionsState = ps.getPermissionsState();
8416        for (int i=0; i<permissions.length; i++) {
8417            final String permission = permissions[i];
8418            if (permissionsState.hasPermission(permission, userId)) {
8419                tmp[i] = true;
8420                numMatch++;
8421            } else {
8422                tmp[i] = false;
8423            }
8424        }
8425        if (numMatch == 0) {
8426            return;
8427        }
8428        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8429
8430        // The above might return null in cases of uninstalled apps or install-state
8431        // skew across users/profiles.
8432        if (pi != null) {
8433            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8434                if (numMatch == permissions.length) {
8435                    pi.requestedPermissions = permissions;
8436                } else {
8437                    pi.requestedPermissions = new String[numMatch];
8438                    numMatch = 0;
8439                    for (int i=0; i<permissions.length; i++) {
8440                        if (tmp[i]) {
8441                            pi.requestedPermissions[numMatch] = permissions[i];
8442                            numMatch++;
8443                        }
8444                    }
8445                }
8446            }
8447            list.add(pi);
8448        }
8449    }
8450
8451    @Override
8452    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8453            String[] permissions, int flags, int userId) {
8454        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8455        flags = updateFlagsForPackage(flags, userId, permissions);
8456        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8457                true /* requireFullPermission */, false /* checkShell */,
8458                "get packages holding permissions");
8459        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8460
8461        // writer
8462        synchronized (mPackages) {
8463            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8464            boolean[] tmpBools = new boolean[permissions.length];
8465            if (listUninstalled) {
8466                for (PackageSetting ps : mSettings.mPackages.values()) {
8467                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8468                            userId);
8469                }
8470            } else {
8471                for (PackageParser.Package pkg : mPackages.values()) {
8472                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8473                    if (ps != null) {
8474                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8475                                userId);
8476                    }
8477                }
8478            }
8479
8480            return new ParceledListSlice<PackageInfo>(list);
8481        }
8482    }
8483
8484    @Override
8485    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8486        final int callingUid = Binder.getCallingUid();
8487        if (getInstantAppPackageName(callingUid) != null) {
8488            return ParceledListSlice.emptyList();
8489        }
8490        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8491        flags = updateFlagsForApplication(flags, userId, null);
8492        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8493
8494        // writer
8495        synchronized (mPackages) {
8496            ArrayList<ApplicationInfo> list;
8497            if (listUninstalled) {
8498                list = new ArrayList<>(mSettings.mPackages.size());
8499                for (PackageSetting ps : mSettings.mPackages.values()) {
8500                    ApplicationInfo ai;
8501                    int effectiveFlags = flags;
8502                    if (ps.isSystem()) {
8503                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8504                    }
8505                    if (ps.pkg != null) {
8506                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8507                            continue;
8508                        }
8509                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8510                            return null;
8511                        }
8512                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8513                                ps.readUserState(userId), userId);
8514                        if (ai != null) {
8515                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8516                        }
8517                    } else {
8518                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8519                        // and already converts to externally visible package name
8520                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8521                                callingUid, effectiveFlags, userId);
8522                    }
8523                    if (ai != null) {
8524                        list.add(ai);
8525                    }
8526                }
8527            } else {
8528                list = new ArrayList<>(mPackages.size());
8529                for (PackageParser.Package p : mPackages.values()) {
8530                    if (p.mExtras != null) {
8531                        PackageSetting ps = (PackageSetting) p.mExtras;
8532                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8533                            continue;
8534                        }
8535                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8536                            return null;
8537                        }
8538                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8539                                ps.readUserState(userId), userId);
8540                        if (ai != null) {
8541                            ai.packageName = resolveExternalPackageNameLPr(p);
8542                            list.add(ai);
8543                        }
8544                    }
8545                }
8546            }
8547
8548            return new ParceledListSlice<>(list);
8549        }
8550    }
8551
8552    @Override
8553    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8554        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8555            return null;
8556        }
8557        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8558            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8559                    "getEphemeralApplications");
8560        }
8561        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8562                true /* requireFullPermission */, false /* checkShell */,
8563                "getEphemeralApplications");
8564        synchronized (mPackages) {
8565            List<InstantAppInfo> instantApps = mInstantAppRegistry
8566                    .getInstantAppsLPr(userId);
8567            if (instantApps != null) {
8568                return new ParceledListSlice<>(instantApps);
8569            }
8570        }
8571        return null;
8572    }
8573
8574    @Override
8575    public boolean isInstantApp(String packageName, int userId) {
8576        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8577                true /* requireFullPermission */, false /* checkShell */,
8578                "isInstantApp");
8579        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8580            return false;
8581        }
8582
8583        synchronized (mPackages) {
8584            int callingUid = Binder.getCallingUid();
8585            if (Process.isIsolated(callingUid)) {
8586                callingUid = mIsolatedOwners.get(callingUid);
8587            }
8588            final PackageSetting ps = mSettings.mPackages.get(packageName);
8589            PackageParser.Package pkg = mPackages.get(packageName);
8590            final boolean returnAllowed =
8591                    ps != null
8592                    && (isCallerSameApp(packageName, callingUid)
8593                            || canViewInstantApps(callingUid, userId)
8594                            || mInstantAppRegistry.isInstantAccessGranted(
8595                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8596            if (returnAllowed) {
8597                return ps.getInstantApp(userId);
8598            }
8599        }
8600        return false;
8601    }
8602
8603    @Override
8604    public byte[] getInstantAppCookie(String packageName, int userId) {
8605        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8606            return null;
8607        }
8608
8609        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8610                true /* requireFullPermission */, false /* checkShell */,
8611                "getInstantAppCookie");
8612        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8613            return null;
8614        }
8615        synchronized (mPackages) {
8616            return mInstantAppRegistry.getInstantAppCookieLPw(
8617                    packageName, userId);
8618        }
8619    }
8620
8621    @Override
8622    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8623        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8624            return true;
8625        }
8626
8627        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8628                true /* requireFullPermission */, true /* checkShell */,
8629                "setInstantAppCookie");
8630        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8631            return false;
8632        }
8633        synchronized (mPackages) {
8634            return mInstantAppRegistry.setInstantAppCookieLPw(
8635                    packageName, cookie, userId);
8636        }
8637    }
8638
8639    @Override
8640    public Bitmap getInstantAppIcon(String packageName, int userId) {
8641        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8642            return null;
8643        }
8644
8645        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8646            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8647                    "getInstantAppIcon");
8648        }
8649        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8650                true /* requireFullPermission */, false /* checkShell */,
8651                "getInstantAppIcon");
8652
8653        synchronized (mPackages) {
8654            return mInstantAppRegistry.getInstantAppIconLPw(
8655                    packageName, userId);
8656        }
8657    }
8658
8659    private boolean isCallerSameApp(String packageName, int uid) {
8660        PackageParser.Package pkg = mPackages.get(packageName);
8661        return pkg != null
8662                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8663    }
8664
8665    @Override
8666    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8667        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8668            return ParceledListSlice.emptyList();
8669        }
8670        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8671    }
8672
8673    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8674        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8675
8676        // reader
8677        synchronized (mPackages) {
8678            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8679            final int userId = UserHandle.getCallingUserId();
8680            while (i.hasNext()) {
8681                final PackageParser.Package p = i.next();
8682                if (p.applicationInfo == null) continue;
8683
8684                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8685                        && !p.applicationInfo.isDirectBootAware();
8686                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8687                        && p.applicationInfo.isDirectBootAware();
8688
8689                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8690                        && (!mSafeMode || isSystemApp(p))
8691                        && (matchesUnaware || matchesAware)) {
8692                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8693                    if (ps != null) {
8694                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8695                                ps.readUserState(userId), userId);
8696                        if (ai != null) {
8697                            finalList.add(ai);
8698                        }
8699                    }
8700                }
8701            }
8702        }
8703
8704        return finalList;
8705    }
8706
8707    @Override
8708    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8709        if (!sUserManager.exists(userId)) return null;
8710        flags = updateFlagsForComponent(flags, userId, name);
8711        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8712        // reader
8713        synchronized (mPackages) {
8714            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8715            PackageSetting ps = provider != null
8716                    ? mSettings.mPackages.get(provider.owner.packageName)
8717                    : null;
8718            if (ps != null) {
8719                final boolean isInstantApp = ps.getInstantApp(userId);
8720                // normal application; filter out instant application provider
8721                if (instantAppPkgName == null && isInstantApp) {
8722                    return null;
8723                }
8724                // instant application; filter out other instant applications
8725                if (instantAppPkgName != null
8726                        && isInstantApp
8727                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8728                    return null;
8729                }
8730                // instant application; filter out non-exposed provider
8731                if (instantAppPkgName != null
8732                        && !isInstantApp
8733                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8734                    return null;
8735                }
8736                // provider not enabled
8737                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8738                    return null;
8739                }
8740                return PackageParser.generateProviderInfo(
8741                        provider, flags, ps.readUserState(userId), userId);
8742            }
8743            return null;
8744        }
8745    }
8746
8747    /**
8748     * @deprecated
8749     */
8750    @Deprecated
8751    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8752        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8753            return;
8754        }
8755        // reader
8756        synchronized (mPackages) {
8757            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8758                    .entrySet().iterator();
8759            final int userId = UserHandle.getCallingUserId();
8760            while (i.hasNext()) {
8761                Map.Entry<String, PackageParser.Provider> entry = i.next();
8762                PackageParser.Provider p = entry.getValue();
8763                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8764
8765                if (ps != null && p.syncable
8766                        && (!mSafeMode || (p.info.applicationInfo.flags
8767                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8768                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8769                            ps.readUserState(userId), userId);
8770                    if (info != null) {
8771                        outNames.add(entry.getKey());
8772                        outInfo.add(info);
8773                    }
8774                }
8775            }
8776        }
8777    }
8778
8779    @Override
8780    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8781            int uid, int flags, String metaDataKey) {
8782        final int callingUid = Binder.getCallingUid();
8783        final int userId = processName != null ? UserHandle.getUserId(uid)
8784                : UserHandle.getCallingUserId();
8785        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8786        flags = updateFlagsForComponent(flags, userId, processName);
8787        ArrayList<ProviderInfo> finalList = null;
8788        // reader
8789        synchronized (mPackages) {
8790            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8791            while (i.hasNext()) {
8792                final PackageParser.Provider p = i.next();
8793                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8794                if (ps != null && p.info.authority != null
8795                        && (processName == null
8796                                || (p.info.processName.equals(processName)
8797                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8798                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8799
8800                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8801                    // parameter.
8802                    if (metaDataKey != null
8803                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8804                        continue;
8805                    }
8806                    final ComponentName component =
8807                            new ComponentName(p.info.packageName, p.info.name);
8808                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8809                        continue;
8810                    }
8811                    if (finalList == null) {
8812                        finalList = new ArrayList<ProviderInfo>(3);
8813                    }
8814                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8815                            ps.readUserState(userId), userId);
8816                    if (info != null) {
8817                        finalList.add(info);
8818                    }
8819                }
8820            }
8821        }
8822
8823        if (finalList != null) {
8824            Collections.sort(finalList, mProviderInitOrderSorter);
8825            return new ParceledListSlice<ProviderInfo>(finalList);
8826        }
8827
8828        return ParceledListSlice.emptyList();
8829    }
8830
8831    @Override
8832    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8833        // reader
8834        synchronized (mPackages) {
8835            final int callingUid = Binder.getCallingUid();
8836            final int callingUserId = UserHandle.getUserId(callingUid);
8837            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8838            if (ps == null) return null;
8839            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8840                return null;
8841            }
8842            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8843            return PackageParser.generateInstrumentationInfo(i, flags);
8844        }
8845    }
8846
8847    @Override
8848    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8849            String targetPackage, int flags) {
8850        final int callingUid = Binder.getCallingUid();
8851        final int callingUserId = UserHandle.getUserId(callingUid);
8852        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8853        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8854            return ParceledListSlice.emptyList();
8855        }
8856        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8857    }
8858
8859    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8860            int flags) {
8861        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8862
8863        // reader
8864        synchronized (mPackages) {
8865            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8866            while (i.hasNext()) {
8867                final PackageParser.Instrumentation p = i.next();
8868                if (targetPackage == null
8869                        || targetPackage.equals(p.info.targetPackage)) {
8870                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8871                            flags);
8872                    if (ii != null) {
8873                        finalList.add(ii);
8874                    }
8875                }
8876            }
8877        }
8878
8879        return finalList;
8880    }
8881
8882    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8883        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8884        try {
8885            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8886        } finally {
8887            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8888        }
8889    }
8890
8891    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8892        final File[] files = dir.listFiles();
8893        if (ArrayUtils.isEmpty(files)) {
8894            Log.d(TAG, "No files in app dir " + dir);
8895            return;
8896        }
8897
8898        if (DEBUG_PACKAGE_SCANNING) {
8899            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8900                    + " flags=0x" + Integer.toHexString(parseFlags));
8901        }
8902        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8903                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8904                mParallelPackageParserCallback);
8905
8906        // Submit files for parsing in parallel
8907        int fileCount = 0;
8908        for (File file : files) {
8909            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8910                    && !PackageInstallerService.isStageName(file.getName());
8911            if (!isPackage) {
8912                // Ignore entries which are not packages
8913                continue;
8914            }
8915            parallelPackageParser.submit(file, parseFlags);
8916            fileCount++;
8917        }
8918
8919        // Process results one by one
8920        for (; fileCount > 0; fileCount--) {
8921            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8922            Throwable throwable = parseResult.throwable;
8923            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8924
8925            if (throwable == null) {
8926                // Static shared libraries have synthetic package names
8927                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8928                    renameStaticSharedLibraryPackage(parseResult.pkg);
8929                }
8930                try {
8931                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8932                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8933                                currentTime, null);
8934                    }
8935                } catch (PackageManagerException e) {
8936                    errorCode = e.error;
8937                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8938                }
8939            } else if (throwable instanceof PackageParser.PackageParserException) {
8940                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8941                        throwable;
8942                errorCode = e.error;
8943                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8944            } else {
8945                throw new IllegalStateException("Unexpected exception occurred while parsing "
8946                        + parseResult.scanFile, throwable);
8947            }
8948
8949            // Delete invalid userdata apps
8950            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8951                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8952                logCriticalInfo(Log.WARN,
8953                        "Deleting invalid package at " + parseResult.scanFile);
8954                removeCodePathLI(parseResult.scanFile);
8955            }
8956        }
8957        parallelPackageParser.close();
8958    }
8959
8960    private static File getSettingsProblemFile() {
8961        File dataDir = Environment.getDataDirectory();
8962        File systemDir = new File(dataDir, "system");
8963        File fname = new File(systemDir, "uiderrors.txt");
8964        return fname;
8965    }
8966
8967    static void reportSettingsProblem(int priority, String msg) {
8968        logCriticalInfo(priority, msg);
8969    }
8970
8971    public static void logCriticalInfo(int priority, String msg) {
8972        Slog.println(priority, TAG, msg);
8973        EventLogTags.writePmCriticalInfo(msg);
8974        try {
8975            File fname = getSettingsProblemFile();
8976            FileOutputStream out = new FileOutputStream(fname, true);
8977            PrintWriter pw = new FastPrintWriter(out);
8978            SimpleDateFormat formatter = new SimpleDateFormat();
8979            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8980            pw.println(dateString + ": " + msg);
8981            pw.close();
8982            FileUtils.setPermissions(
8983                    fname.toString(),
8984                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8985                    -1, -1);
8986        } catch (java.io.IOException e) {
8987        }
8988    }
8989
8990    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8991        if (srcFile.isDirectory()) {
8992            final File baseFile = new File(pkg.baseCodePath);
8993            long maxModifiedTime = baseFile.lastModified();
8994            if (pkg.splitCodePaths != null) {
8995                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8996                    final File splitFile = new File(pkg.splitCodePaths[i]);
8997                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8998                }
8999            }
9000            return maxModifiedTime;
9001        }
9002        return srcFile.lastModified();
9003    }
9004
9005    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9006            final int policyFlags) throws PackageManagerException {
9007        // When upgrading from pre-N MR1, verify the package time stamp using the package
9008        // directory and not the APK file.
9009        final long lastModifiedTime = mIsPreNMR1Upgrade
9010                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9011        if (ps != null
9012                && ps.codePath.equals(srcFile)
9013                && ps.timeStamp == lastModifiedTime
9014                && !isCompatSignatureUpdateNeeded(pkg)
9015                && !isRecoverSignatureUpdateNeeded(pkg)) {
9016            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9017            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9018            ArraySet<PublicKey> signingKs;
9019            synchronized (mPackages) {
9020                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9021            }
9022            if (ps.signatures.mSignatures != null
9023                    && ps.signatures.mSignatures.length != 0
9024                    && signingKs != null) {
9025                // Optimization: reuse the existing cached certificates
9026                // if the package appears to be unchanged.
9027                pkg.mSignatures = ps.signatures.mSignatures;
9028                pkg.mSigningKeys = signingKs;
9029                return;
9030            }
9031
9032            Slog.w(TAG, "PackageSetting for " + ps.name
9033                    + " is missing signatures.  Collecting certs again to recover them.");
9034        } else {
9035            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9036        }
9037
9038        try {
9039            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9040            PackageParser.collectCertificates(pkg, policyFlags);
9041        } catch (PackageParserException e) {
9042            throw PackageManagerException.from(e);
9043        } finally {
9044            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9045        }
9046    }
9047
9048    /**
9049     *  Traces a package scan.
9050     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9051     */
9052    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9053            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9054        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9055        try {
9056            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9057        } finally {
9058            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9059        }
9060    }
9061
9062    /**
9063     *  Scans a package and returns the newly parsed package.
9064     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9065     */
9066    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9067            long currentTime, UserHandle user) throws PackageManagerException {
9068        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9069        PackageParser pp = new PackageParser();
9070        pp.setSeparateProcesses(mSeparateProcesses);
9071        pp.setOnlyCoreApps(mOnlyCore);
9072        pp.setDisplayMetrics(mMetrics);
9073        pp.setCallback(mPackageParserCallback);
9074
9075        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9076            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9077        }
9078
9079        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9080        final PackageParser.Package pkg;
9081        try {
9082            pkg = pp.parsePackage(scanFile, parseFlags);
9083        } catch (PackageParserException e) {
9084            throw PackageManagerException.from(e);
9085        } finally {
9086            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9087        }
9088
9089        // Static shared libraries have synthetic package names
9090        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9091            renameStaticSharedLibraryPackage(pkg);
9092        }
9093
9094        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9095    }
9096
9097    /**
9098     *  Scans a package and returns the newly parsed package.
9099     *  @throws PackageManagerException on a parse error.
9100     */
9101    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9102            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9103            throws PackageManagerException {
9104        // If the package has children and this is the first dive in the function
9105        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9106        // packages (parent and children) would be successfully scanned before the
9107        // actual scan since scanning mutates internal state and we want to atomically
9108        // install the package and its children.
9109        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9110            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9111                scanFlags |= SCAN_CHECK_ONLY;
9112            }
9113        } else {
9114            scanFlags &= ~SCAN_CHECK_ONLY;
9115        }
9116
9117        // Scan the parent
9118        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9119                scanFlags, currentTime, user);
9120
9121        // Scan the children
9122        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9123        for (int i = 0; i < childCount; i++) {
9124            PackageParser.Package childPackage = pkg.childPackages.get(i);
9125            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9126                    currentTime, user);
9127        }
9128
9129
9130        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9131            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9132        }
9133
9134        return scannedPkg;
9135    }
9136
9137    /**
9138     *  Scans a package and returns the newly parsed package.
9139     *  @throws PackageManagerException on a parse error.
9140     */
9141    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9142            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9143            throws PackageManagerException {
9144        PackageSetting ps = null;
9145        PackageSetting updatedPkg;
9146        // reader
9147        synchronized (mPackages) {
9148            // Look to see if we already know about this package.
9149            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9150            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9151                // This package has been renamed to its original name.  Let's
9152                // use that.
9153                ps = mSettings.getPackageLPr(oldName);
9154            }
9155            // If there was no original package, see one for the real package name.
9156            if (ps == null) {
9157                ps = mSettings.getPackageLPr(pkg.packageName);
9158            }
9159            // Check to see if this package could be hiding/updating a system
9160            // package.  Must look for it either under the original or real
9161            // package name depending on our state.
9162            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9163            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9164
9165            // If this is a package we don't know about on the system partition, we
9166            // may need to remove disabled child packages on the system partition
9167            // or may need to not add child packages if the parent apk is updated
9168            // on the data partition and no longer defines this child package.
9169            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9170                // If this is a parent package for an updated system app and this system
9171                // app got an OTA update which no longer defines some of the child packages
9172                // we have to prune them from the disabled system packages.
9173                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9174                if (disabledPs != null) {
9175                    final int scannedChildCount = (pkg.childPackages != null)
9176                            ? pkg.childPackages.size() : 0;
9177                    final int disabledChildCount = disabledPs.childPackageNames != null
9178                            ? disabledPs.childPackageNames.size() : 0;
9179                    for (int i = 0; i < disabledChildCount; i++) {
9180                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9181                        boolean disabledPackageAvailable = false;
9182                        for (int j = 0; j < scannedChildCount; j++) {
9183                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9184                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9185                                disabledPackageAvailable = true;
9186                                break;
9187                            }
9188                         }
9189                         if (!disabledPackageAvailable) {
9190                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9191                         }
9192                    }
9193                }
9194            }
9195        }
9196
9197        final boolean isUpdatedPkg = updatedPkg != null;
9198        final boolean isUpdatedSystemPkg = isUpdatedPkg
9199                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9200        boolean isUpdatedPkgBetter = false;
9201        // First check if this is a system package that may involve an update
9202        if (isUpdatedSystemPkg) {
9203            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9204            // it needs to drop FLAG_PRIVILEGED.
9205            if (locationIsPrivileged(scanFile)) {
9206                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9207            } else {
9208                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9209            }
9210
9211            if (ps != null && !ps.codePath.equals(scanFile)) {
9212                // The path has changed from what was last scanned...  check the
9213                // version of the new path against what we have stored to determine
9214                // what to do.
9215                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9216                if (pkg.mVersionCode <= ps.versionCode) {
9217                    // The system package has been updated and the code path does not match
9218                    // Ignore entry. Skip it.
9219                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9220                            + " ignored: updated version " + ps.versionCode
9221                            + " better than this " + pkg.mVersionCode);
9222                    if (!updatedPkg.codePath.equals(scanFile)) {
9223                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9224                                + ps.name + " changing from " + updatedPkg.codePathString
9225                                + " to " + scanFile);
9226                        updatedPkg.codePath = scanFile;
9227                        updatedPkg.codePathString = scanFile.toString();
9228                        updatedPkg.resourcePath = scanFile;
9229                        updatedPkg.resourcePathString = scanFile.toString();
9230                    }
9231                    updatedPkg.pkg = pkg;
9232                    updatedPkg.versionCode = pkg.mVersionCode;
9233
9234                    // Update the disabled system child packages to point to the package too.
9235                    final int childCount = updatedPkg.childPackageNames != null
9236                            ? updatedPkg.childPackageNames.size() : 0;
9237                    for (int i = 0; i < childCount; i++) {
9238                        String childPackageName = updatedPkg.childPackageNames.get(i);
9239                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9240                                childPackageName);
9241                        if (updatedChildPkg != null) {
9242                            updatedChildPkg.pkg = pkg;
9243                            updatedChildPkg.versionCode = pkg.mVersionCode;
9244                        }
9245                    }
9246                } else {
9247                    // The current app on the system partition is better than
9248                    // what we have updated to on the data partition; switch
9249                    // back to the system partition version.
9250                    // At this point, its safely assumed that package installation for
9251                    // apps in system partition will go through. If not there won't be a working
9252                    // version of the app
9253                    // writer
9254                    synchronized (mPackages) {
9255                        // Just remove the loaded entries from package lists.
9256                        mPackages.remove(ps.name);
9257                    }
9258
9259                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9260                            + " reverting from " + ps.codePathString
9261                            + ": new version " + pkg.mVersionCode
9262                            + " better than installed " + ps.versionCode);
9263
9264                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9265                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9266                    synchronized (mInstallLock) {
9267                        args.cleanUpResourcesLI();
9268                    }
9269                    synchronized (mPackages) {
9270                        mSettings.enableSystemPackageLPw(ps.name);
9271                    }
9272                    isUpdatedPkgBetter = true;
9273                }
9274            }
9275        }
9276
9277        String resourcePath = null;
9278        String baseResourcePath = null;
9279        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9280            if (ps != null && ps.resourcePathString != null) {
9281                resourcePath = ps.resourcePathString;
9282                baseResourcePath = ps.resourcePathString;
9283            } else {
9284                // Should not happen at all. Just log an error.
9285                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9286            }
9287        } else {
9288            resourcePath = pkg.codePath;
9289            baseResourcePath = pkg.baseCodePath;
9290        }
9291
9292        // Set application objects path explicitly.
9293        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9294        pkg.setApplicationInfoCodePath(pkg.codePath);
9295        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9296        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9297        pkg.setApplicationInfoResourcePath(resourcePath);
9298        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9299        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9300
9301        // throw an exception if we have an update to a system application, but, it's not more
9302        // recent than the package we've already scanned
9303        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9304            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9305                    + scanFile + " ignored: updated version " + ps.versionCode
9306                    + " better than this " + pkg.mVersionCode);
9307        }
9308
9309        if (isUpdatedPkg) {
9310            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9311            // initially
9312            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9313
9314            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9315            // flag set initially
9316            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9317                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9318            }
9319        }
9320
9321        // Verify certificates against what was last scanned
9322        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9323
9324        /*
9325         * A new system app appeared, but we already had a non-system one of the
9326         * same name installed earlier.
9327         */
9328        boolean shouldHideSystemApp = false;
9329        if (!isUpdatedPkg && ps != null
9330                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9331            /*
9332             * Check to make sure the signatures match first. If they don't,
9333             * wipe the installed application and its data.
9334             */
9335            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9336                    != PackageManager.SIGNATURE_MATCH) {
9337                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9338                        + " signatures don't match existing userdata copy; removing");
9339                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9340                        "scanPackageInternalLI")) {
9341                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9342                }
9343                ps = null;
9344            } else {
9345                /*
9346                 * If the newly-added system app is an older version than the
9347                 * already installed version, hide it. It will be scanned later
9348                 * and re-added like an update.
9349                 */
9350                if (pkg.mVersionCode <= ps.versionCode) {
9351                    shouldHideSystemApp = true;
9352                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9353                            + " but new version " + pkg.mVersionCode + " better than installed "
9354                            + ps.versionCode + "; hiding system");
9355                } else {
9356                    /*
9357                     * The newly found system app is a newer version that the
9358                     * one previously installed. Simply remove the
9359                     * already-installed application and replace it with our own
9360                     * while keeping the application data.
9361                     */
9362                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9363                            + " reverting from " + ps.codePathString + ": new version "
9364                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9365                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9366                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9367                    synchronized (mInstallLock) {
9368                        args.cleanUpResourcesLI();
9369                    }
9370                }
9371            }
9372        }
9373
9374        // The apk is forward locked (not public) if its code and resources
9375        // are kept in different files. (except for app in either system or
9376        // vendor path).
9377        // TODO grab this value from PackageSettings
9378        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9379            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9380                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9381            }
9382        }
9383
9384        final int userId = ((user == null) ? 0 : user.getIdentifier());
9385        if (ps != null && ps.getInstantApp(userId)) {
9386            scanFlags |= SCAN_AS_INSTANT_APP;
9387        }
9388
9389        // Note that we invoke the following method only if we are about to unpack an application
9390        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9391                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9392
9393        /*
9394         * If the system app should be overridden by a previously installed
9395         * data, hide the system app now and let the /data/app scan pick it up
9396         * again.
9397         */
9398        if (shouldHideSystemApp) {
9399            synchronized (mPackages) {
9400                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9401            }
9402        }
9403
9404        return scannedPkg;
9405    }
9406
9407    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9408        // Derive the new package synthetic package name
9409        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9410                + pkg.staticSharedLibVersion);
9411    }
9412
9413    private static String fixProcessName(String defProcessName,
9414            String processName) {
9415        if (processName == null) {
9416            return defProcessName;
9417        }
9418        return processName;
9419    }
9420
9421    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9422            throws PackageManagerException {
9423        if (pkgSetting.signatures.mSignatures != null) {
9424            // Already existing package. Make sure signatures match
9425            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9426                    == PackageManager.SIGNATURE_MATCH;
9427            if (!match) {
9428                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9429                        == PackageManager.SIGNATURE_MATCH;
9430            }
9431            if (!match) {
9432                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9433                        == PackageManager.SIGNATURE_MATCH;
9434            }
9435            if (!match) {
9436                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9437                        + pkg.packageName + " signatures do not match the "
9438                        + "previously installed version; ignoring!");
9439            }
9440        }
9441
9442        // Check for shared user signatures
9443        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9444            // Already existing package. Make sure signatures match
9445            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9446                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9447            if (!match) {
9448                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9449                        == PackageManager.SIGNATURE_MATCH;
9450            }
9451            if (!match) {
9452                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9453                        == PackageManager.SIGNATURE_MATCH;
9454            }
9455            if (!match) {
9456                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9457                        "Package " + pkg.packageName
9458                        + " has no signatures that match those in shared user "
9459                        + pkgSetting.sharedUser.name + "; ignoring!");
9460            }
9461        }
9462    }
9463
9464    /**
9465     * Enforces that only the system UID or root's UID can call a method exposed
9466     * via Binder.
9467     *
9468     * @param message used as message if SecurityException is thrown
9469     * @throws SecurityException if the caller is not system or root
9470     */
9471    private static final void enforceSystemOrRoot(String message) {
9472        final int uid = Binder.getCallingUid();
9473        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9474            throw new SecurityException(message);
9475        }
9476    }
9477
9478    @Override
9479    public void performFstrimIfNeeded() {
9480        enforceSystemOrRoot("Only the system can request fstrim");
9481
9482        // Before everything else, see whether we need to fstrim.
9483        try {
9484            IStorageManager sm = PackageHelper.getStorageManager();
9485            if (sm != null) {
9486                boolean doTrim = false;
9487                final long interval = android.provider.Settings.Global.getLong(
9488                        mContext.getContentResolver(),
9489                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9490                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9491                if (interval > 0) {
9492                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9493                    if (timeSinceLast > interval) {
9494                        doTrim = true;
9495                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9496                                + "; running immediately");
9497                    }
9498                }
9499                if (doTrim) {
9500                    final boolean dexOptDialogShown;
9501                    synchronized (mPackages) {
9502                        dexOptDialogShown = mDexOptDialogShown;
9503                    }
9504                    if (!isFirstBoot() && dexOptDialogShown) {
9505                        try {
9506                            ActivityManager.getService().showBootMessage(
9507                                    mContext.getResources().getString(
9508                                            R.string.android_upgrading_fstrim), true);
9509                        } catch (RemoteException e) {
9510                        }
9511                    }
9512                    sm.runMaintenance();
9513                }
9514            } else {
9515                Slog.e(TAG, "storageManager service unavailable!");
9516            }
9517        } catch (RemoteException e) {
9518            // Can't happen; StorageManagerService is local
9519        }
9520    }
9521
9522    @Override
9523    public void updatePackagesIfNeeded() {
9524        enforceSystemOrRoot("Only the system can request package update");
9525
9526        // We need to re-extract after an OTA.
9527        boolean causeUpgrade = isUpgrade();
9528
9529        // First boot or factory reset.
9530        // Note: we also handle devices that are upgrading to N right now as if it is their
9531        //       first boot, as they do not have profile data.
9532        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9533
9534        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9535        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9536
9537        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9538            return;
9539        }
9540
9541        List<PackageParser.Package> pkgs;
9542        synchronized (mPackages) {
9543            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9544        }
9545
9546        final long startTime = System.nanoTime();
9547        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9548                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9549                    false /* bootComplete */);
9550
9551        final int elapsedTimeSeconds =
9552                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9553
9554        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9555        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9556        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9557        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9558        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9559    }
9560
9561    /*
9562     * Return the prebuilt profile path given a package base code path.
9563     */
9564    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9565        return pkg.baseCodePath + ".prof";
9566    }
9567
9568    /**
9569     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9570     * containing statistics about the invocation. The array consists of three elements,
9571     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9572     * and {@code numberOfPackagesFailed}.
9573     */
9574    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9575            String compilerFilter, boolean bootComplete) {
9576
9577        int numberOfPackagesVisited = 0;
9578        int numberOfPackagesOptimized = 0;
9579        int numberOfPackagesSkipped = 0;
9580        int numberOfPackagesFailed = 0;
9581        final int numberOfPackagesToDexopt = pkgs.size();
9582
9583        for (PackageParser.Package pkg : pkgs) {
9584            numberOfPackagesVisited++;
9585
9586            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9587                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9588                // that are already compiled.
9589                File profileFile = new File(getPrebuildProfilePath(pkg));
9590                // Copy profile if it exists.
9591                if (profileFile.exists()) {
9592                    try {
9593                        // We could also do this lazily before calling dexopt in
9594                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9595                        // is that we don't have a good way to say "do this only once".
9596                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9597                                pkg.applicationInfo.uid, pkg.packageName)) {
9598                            Log.e(TAG, "Installer failed to copy system profile!");
9599                        }
9600                    } catch (Exception e) {
9601                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9602                                e);
9603                    }
9604                }
9605            }
9606
9607            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9608                if (DEBUG_DEXOPT) {
9609                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9610                }
9611                numberOfPackagesSkipped++;
9612                continue;
9613            }
9614
9615            if (DEBUG_DEXOPT) {
9616                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9617                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9618            }
9619
9620            if (showDialog) {
9621                try {
9622                    ActivityManager.getService().showBootMessage(
9623                            mContext.getResources().getString(R.string.android_upgrading_apk,
9624                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9625                } catch (RemoteException e) {
9626                }
9627                synchronized (mPackages) {
9628                    mDexOptDialogShown = true;
9629                }
9630            }
9631
9632            // If the OTA updates a system app which was previously preopted to a non-preopted state
9633            // the app might end up being verified at runtime. That's because by default the apps
9634            // are verify-profile but for preopted apps there's no profile.
9635            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9636            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9637            // filter (by default 'quicken').
9638            // Note that at this stage unused apps are already filtered.
9639            if (isSystemApp(pkg) &&
9640                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9641                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9642                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9643            }
9644
9645            // checkProfiles is false to avoid merging profiles during boot which
9646            // might interfere with background compilation (b/28612421).
9647            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9648            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9649            // trade-off worth doing to save boot time work.
9650            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9651            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9652                    pkg.packageName,
9653                    compilerFilter,
9654                    dexoptFlags));
9655
9656            if (pkg.isSystemApp()) {
9657                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9658                // too much boot after an OTA.
9659                int secondaryDexoptFlags = dexoptFlags |
9660                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9661                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9662                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9663                        pkg.packageName,
9664                        compilerFilter,
9665                        secondaryDexoptFlags));
9666            }
9667
9668            // TODO(shubhamajmera): Record secondary dexopt stats.
9669            switch (primaryDexOptStaus) {
9670                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9671                    numberOfPackagesOptimized++;
9672                    break;
9673                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9674                    numberOfPackagesSkipped++;
9675                    break;
9676                case PackageDexOptimizer.DEX_OPT_FAILED:
9677                    numberOfPackagesFailed++;
9678                    break;
9679                default:
9680                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9681                    break;
9682            }
9683        }
9684
9685        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9686                numberOfPackagesFailed };
9687    }
9688
9689    @Override
9690    public void notifyPackageUse(String packageName, int reason) {
9691        synchronized (mPackages) {
9692            final int callingUid = Binder.getCallingUid();
9693            final int callingUserId = UserHandle.getUserId(callingUid);
9694            if (getInstantAppPackageName(callingUid) != null) {
9695                if (!isCallerSameApp(packageName, callingUid)) {
9696                    return;
9697                }
9698            } else {
9699                if (isInstantApp(packageName, callingUserId)) {
9700                    return;
9701                }
9702            }
9703            final PackageParser.Package p = mPackages.get(packageName);
9704            if (p == null) {
9705                return;
9706            }
9707            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9708        }
9709    }
9710
9711    @Override
9712    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9713            List<String> classPaths, String loaderIsa) {
9714        int userId = UserHandle.getCallingUserId();
9715        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9716        if (ai == null) {
9717            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9718                + loadingPackageName + ", user=" + userId);
9719            return;
9720        }
9721        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9722    }
9723
9724    @Override
9725    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9726            IDexModuleRegisterCallback callback) {
9727        int userId = UserHandle.getCallingUserId();
9728        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9729        DexManager.RegisterDexModuleResult result;
9730        if (ai == null) {
9731            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9732                     " calling user. package=" + packageName + ", user=" + userId);
9733            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9734        } else {
9735            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9736        }
9737
9738        if (callback != null) {
9739            mHandler.post(() -> {
9740                try {
9741                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9742                } catch (RemoteException e) {
9743                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9744                }
9745            });
9746        }
9747    }
9748
9749    /**
9750     * Ask the package manager to perform a dex-opt with the given compiler filter.
9751     *
9752     * Note: exposed only for the shell command to allow moving packages explicitly to a
9753     *       definite state.
9754     */
9755    @Override
9756    public boolean performDexOptMode(String packageName,
9757            boolean checkProfiles, String targetCompilerFilter, boolean force,
9758            boolean bootComplete, String splitName) {
9759        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9760                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9761                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9762        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9763                splitName, flags));
9764    }
9765
9766    /**
9767     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9768     * secondary dex files belonging to the given package.
9769     *
9770     * Note: exposed only for the shell command to allow moving packages explicitly to a
9771     *       definite state.
9772     */
9773    @Override
9774    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9775            boolean force) {
9776        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9777                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9778                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9779                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9780        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9781    }
9782
9783    /*package*/ boolean performDexOpt(DexoptOptions options) {
9784        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9785            return false;
9786        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9787            return false;
9788        }
9789
9790        if (options.isDexoptOnlySecondaryDex()) {
9791            return mDexManager.dexoptSecondaryDex(options);
9792        } else {
9793            int dexoptStatus = performDexOptWithStatus(options);
9794            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9795        }
9796    }
9797
9798    /**
9799     * Perform dexopt on the given package and return one of following result:
9800     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9801     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9802     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9803     */
9804    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9805        return performDexOptTraced(options);
9806    }
9807
9808    private int performDexOptTraced(DexoptOptions options) {
9809        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9810        try {
9811            return performDexOptInternal(options);
9812        } finally {
9813            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9814        }
9815    }
9816
9817    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9818    // if the package can now be considered up to date for the given filter.
9819    private int performDexOptInternal(DexoptOptions options) {
9820        PackageParser.Package p;
9821        synchronized (mPackages) {
9822            p = mPackages.get(options.getPackageName());
9823            if (p == null) {
9824                // Package could not be found. Report failure.
9825                return PackageDexOptimizer.DEX_OPT_FAILED;
9826            }
9827            mPackageUsage.maybeWriteAsync(mPackages);
9828            mCompilerStats.maybeWriteAsync();
9829        }
9830        long callingId = Binder.clearCallingIdentity();
9831        try {
9832            synchronized (mInstallLock) {
9833                return performDexOptInternalWithDependenciesLI(p, options);
9834            }
9835        } finally {
9836            Binder.restoreCallingIdentity(callingId);
9837        }
9838    }
9839
9840    public ArraySet<String> getOptimizablePackages() {
9841        ArraySet<String> pkgs = new ArraySet<String>();
9842        synchronized (mPackages) {
9843            for (PackageParser.Package p : mPackages.values()) {
9844                if (PackageDexOptimizer.canOptimizePackage(p)) {
9845                    pkgs.add(p.packageName);
9846                }
9847            }
9848        }
9849        return pkgs;
9850    }
9851
9852    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9853            DexoptOptions options) {
9854        // Select the dex optimizer based on the force parameter.
9855        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9856        //       allocate an object here.
9857        PackageDexOptimizer pdo = options.isForce()
9858                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9859                : mPackageDexOptimizer;
9860
9861        // Dexopt all dependencies first. Note: we ignore the return value and march on
9862        // on errors.
9863        // Note that we are going to call performDexOpt on those libraries as many times as
9864        // they are referenced in packages. When we do a batch of performDexOpt (for example
9865        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9866        // and the first package that uses the library will dexopt it. The
9867        // others will see that the compiled code for the library is up to date.
9868        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9869        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9870        if (!deps.isEmpty()) {
9871            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9872                    options.getCompilerFilter(), options.getSplitName(),
9873                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9874            for (PackageParser.Package depPackage : deps) {
9875                // TODO: Analyze and investigate if we (should) profile libraries.
9876                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9877                        getOrCreateCompilerPackageStats(depPackage),
9878                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9879            }
9880        }
9881        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9882                getOrCreateCompilerPackageStats(p),
9883                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9884    }
9885
9886    /**
9887     * Reconcile the information we have about the secondary dex files belonging to
9888     * {@code packagName} and the actual dex files. For all dex files that were
9889     * deleted, update the internal records and delete the generated oat files.
9890     */
9891    @Override
9892    public void reconcileSecondaryDexFiles(String packageName) {
9893        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9894            return;
9895        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9896            return;
9897        }
9898        mDexManager.reconcileSecondaryDexFiles(packageName);
9899    }
9900
9901    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9902    // a reference there.
9903    /*package*/ DexManager getDexManager() {
9904        return mDexManager;
9905    }
9906
9907    /**
9908     * Execute the background dexopt job immediately.
9909     */
9910    @Override
9911    public boolean runBackgroundDexoptJob() {
9912        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9913            return false;
9914        }
9915        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9916    }
9917
9918    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9919        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9920                || p.usesStaticLibraries != null) {
9921            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9922            Set<String> collectedNames = new HashSet<>();
9923            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9924
9925            retValue.remove(p);
9926
9927            return retValue;
9928        } else {
9929            return Collections.emptyList();
9930        }
9931    }
9932
9933    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9934            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9935        if (!collectedNames.contains(p.packageName)) {
9936            collectedNames.add(p.packageName);
9937            collected.add(p);
9938
9939            if (p.usesLibraries != null) {
9940                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9941                        null, collected, collectedNames);
9942            }
9943            if (p.usesOptionalLibraries != null) {
9944                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9945                        null, collected, collectedNames);
9946            }
9947            if (p.usesStaticLibraries != null) {
9948                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9949                        p.usesStaticLibrariesVersions, collected, collectedNames);
9950            }
9951        }
9952    }
9953
9954    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9955            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9956        final int libNameCount = libs.size();
9957        for (int i = 0; i < libNameCount; i++) {
9958            String libName = libs.get(i);
9959            int version = (versions != null && versions.length == libNameCount)
9960                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9961            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9962            if (libPkg != null) {
9963                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9964            }
9965        }
9966    }
9967
9968    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9969        synchronized (mPackages) {
9970            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9971            if (libEntry != null) {
9972                return mPackages.get(libEntry.apk);
9973            }
9974            return null;
9975        }
9976    }
9977
9978    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9979        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9980        if (versionedLib == null) {
9981            return null;
9982        }
9983        return versionedLib.get(version);
9984    }
9985
9986    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9987        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9988                pkg.staticSharedLibName);
9989        if (versionedLib == null) {
9990            return null;
9991        }
9992        int previousLibVersion = -1;
9993        final int versionCount = versionedLib.size();
9994        for (int i = 0; i < versionCount; i++) {
9995            final int libVersion = versionedLib.keyAt(i);
9996            if (libVersion < pkg.staticSharedLibVersion) {
9997                previousLibVersion = Math.max(previousLibVersion, libVersion);
9998            }
9999        }
10000        if (previousLibVersion >= 0) {
10001            return versionedLib.get(previousLibVersion);
10002        }
10003        return null;
10004    }
10005
10006    public void shutdown() {
10007        mPackageUsage.writeNow(mPackages);
10008        mCompilerStats.writeNow();
10009        mDexManager.writePackageDexUsageNow();
10010    }
10011
10012    @Override
10013    public void dumpProfiles(String packageName) {
10014        PackageParser.Package pkg;
10015        synchronized (mPackages) {
10016            pkg = mPackages.get(packageName);
10017            if (pkg == null) {
10018                throw new IllegalArgumentException("Unknown package: " + packageName);
10019            }
10020        }
10021        /* Only the shell, root, or the app user should be able to dump profiles. */
10022        int callingUid = Binder.getCallingUid();
10023        if (callingUid != Process.SHELL_UID &&
10024            callingUid != Process.ROOT_UID &&
10025            callingUid != pkg.applicationInfo.uid) {
10026            throw new SecurityException("dumpProfiles");
10027        }
10028
10029        synchronized (mInstallLock) {
10030            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10031            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10032            try {
10033                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10034                String codePaths = TextUtils.join(";", allCodePaths);
10035                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10036            } catch (InstallerException e) {
10037                Slog.w(TAG, "Failed to dump profiles", e);
10038            }
10039            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10040        }
10041    }
10042
10043    @Override
10044    public void forceDexOpt(String packageName) {
10045        enforceSystemOrRoot("forceDexOpt");
10046
10047        PackageParser.Package pkg;
10048        synchronized (mPackages) {
10049            pkg = mPackages.get(packageName);
10050            if (pkg == null) {
10051                throw new IllegalArgumentException("Unknown package: " + packageName);
10052            }
10053        }
10054
10055        synchronized (mInstallLock) {
10056            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10057
10058            // Whoever is calling forceDexOpt wants a compiled package.
10059            // Don't use profiles since that may cause compilation to be skipped.
10060            final int res = performDexOptInternalWithDependenciesLI(
10061                    pkg,
10062                    new DexoptOptions(packageName,
10063                            getDefaultCompilerFilter(),
10064                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10065
10066            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10067            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10068                throw new IllegalStateException("Failed to dexopt: " + res);
10069            }
10070        }
10071    }
10072
10073    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10074        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10075            Slog.w(TAG, "Unable to update from " + oldPkg.name
10076                    + " to " + newPkg.packageName
10077                    + ": old package not in system partition");
10078            return false;
10079        } else if (mPackages.get(oldPkg.name) != null) {
10080            Slog.w(TAG, "Unable to update from " + oldPkg.name
10081                    + " to " + newPkg.packageName
10082                    + ": old package still exists");
10083            return false;
10084        }
10085        return true;
10086    }
10087
10088    void removeCodePathLI(File codePath) {
10089        if (codePath.isDirectory()) {
10090            try {
10091                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10092            } catch (InstallerException e) {
10093                Slog.w(TAG, "Failed to remove code path", e);
10094            }
10095        } else {
10096            codePath.delete();
10097        }
10098    }
10099
10100    private int[] resolveUserIds(int userId) {
10101        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10102    }
10103
10104    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10105        if (pkg == null) {
10106            Slog.wtf(TAG, "Package was null!", new Throwable());
10107            return;
10108        }
10109        clearAppDataLeafLIF(pkg, userId, flags);
10110        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10111        for (int i = 0; i < childCount; i++) {
10112            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10113        }
10114    }
10115
10116    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10117        final PackageSetting ps;
10118        synchronized (mPackages) {
10119            ps = mSettings.mPackages.get(pkg.packageName);
10120        }
10121        for (int realUserId : resolveUserIds(userId)) {
10122            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10123            try {
10124                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10125                        ceDataInode);
10126            } catch (InstallerException e) {
10127                Slog.w(TAG, String.valueOf(e));
10128            }
10129        }
10130    }
10131
10132    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10133        if (pkg == null) {
10134            Slog.wtf(TAG, "Package was null!", new Throwable());
10135            return;
10136        }
10137        destroyAppDataLeafLIF(pkg, userId, flags);
10138        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10139        for (int i = 0; i < childCount; i++) {
10140            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10141        }
10142    }
10143
10144    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10145        final PackageSetting ps;
10146        synchronized (mPackages) {
10147            ps = mSettings.mPackages.get(pkg.packageName);
10148        }
10149        for (int realUserId : resolveUserIds(userId)) {
10150            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10151            try {
10152                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10153                        ceDataInode);
10154            } catch (InstallerException e) {
10155                Slog.w(TAG, String.valueOf(e));
10156            }
10157            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10158        }
10159    }
10160
10161    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10162        if (pkg == null) {
10163            Slog.wtf(TAG, "Package was null!", new Throwable());
10164            return;
10165        }
10166        destroyAppProfilesLeafLIF(pkg);
10167        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10168        for (int i = 0; i < childCount; i++) {
10169            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10170        }
10171    }
10172
10173    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10174        try {
10175            mInstaller.destroyAppProfiles(pkg.packageName);
10176        } catch (InstallerException e) {
10177            Slog.w(TAG, String.valueOf(e));
10178        }
10179    }
10180
10181    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10182        if (pkg == null) {
10183            Slog.wtf(TAG, "Package was null!", new Throwable());
10184            return;
10185        }
10186        clearAppProfilesLeafLIF(pkg);
10187        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10188        for (int i = 0; i < childCount; i++) {
10189            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10190        }
10191    }
10192
10193    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10194        try {
10195            mInstaller.clearAppProfiles(pkg.packageName);
10196        } catch (InstallerException e) {
10197            Slog.w(TAG, String.valueOf(e));
10198        }
10199    }
10200
10201    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10202            long lastUpdateTime) {
10203        // Set parent install/update time
10204        PackageSetting ps = (PackageSetting) pkg.mExtras;
10205        if (ps != null) {
10206            ps.firstInstallTime = firstInstallTime;
10207            ps.lastUpdateTime = lastUpdateTime;
10208        }
10209        // Set children install/update time
10210        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10211        for (int i = 0; i < childCount; i++) {
10212            PackageParser.Package childPkg = pkg.childPackages.get(i);
10213            ps = (PackageSetting) childPkg.mExtras;
10214            if (ps != null) {
10215                ps.firstInstallTime = firstInstallTime;
10216                ps.lastUpdateTime = lastUpdateTime;
10217            }
10218        }
10219    }
10220
10221    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10222            PackageParser.Package changingLib) {
10223        if (file.path != null) {
10224            usesLibraryFiles.add(file.path);
10225            return;
10226        }
10227        PackageParser.Package p = mPackages.get(file.apk);
10228        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10229            // If we are doing this while in the middle of updating a library apk,
10230            // then we need to make sure to use that new apk for determining the
10231            // dependencies here.  (We haven't yet finished committing the new apk
10232            // to the package manager state.)
10233            if (p == null || p.packageName.equals(changingLib.packageName)) {
10234                p = changingLib;
10235            }
10236        }
10237        if (p != null) {
10238            usesLibraryFiles.addAll(p.getAllCodePaths());
10239            if (p.usesLibraryFiles != null) {
10240                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10241            }
10242        }
10243    }
10244
10245    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10246            PackageParser.Package changingLib) throws PackageManagerException {
10247        if (pkg == null) {
10248            return;
10249        }
10250        ArraySet<String> usesLibraryFiles = null;
10251        if (pkg.usesLibraries != null) {
10252            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10253                    null, null, pkg.packageName, changingLib, true, null);
10254        }
10255        if (pkg.usesStaticLibraries != null) {
10256            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10257                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10258                    pkg.packageName, changingLib, true, usesLibraryFiles);
10259        }
10260        if (pkg.usesOptionalLibraries != null) {
10261            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10262                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10263        }
10264        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10265            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10266        } else {
10267            pkg.usesLibraryFiles = null;
10268        }
10269    }
10270
10271    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10272            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10273            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10274            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10275            throws PackageManagerException {
10276        final int libCount = requestedLibraries.size();
10277        for (int i = 0; i < libCount; i++) {
10278            final String libName = requestedLibraries.get(i);
10279            final int libVersion = requiredVersions != null ? requiredVersions[i]
10280                    : SharedLibraryInfo.VERSION_UNDEFINED;
10281            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10282            if (libEntry == null) {
10283                if (required) {
10284                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10285                            "Package " + packageName + " requires unavailable shared library "
10286                                    + libName + "; failing!");
10287                } else if (DEBUG_SHARED_LIBRARIES) {
10288                    Slog.i(TAG, "Package " + packageName
10289                            + " desires unavailable shared library "
10290                            + libName + "; ignoring!");
10291                }
10292            } else {
10293                if (requiredVersions != null && requiredCertDigests != null) {
10294                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10295                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10296                            "Package " + packageName + " requires unavailable static shared"
10297                                    + " library " + libName + " version "
10298                                    + libEntry.info.getVersion() + "; failing!");
10299                    }
10300
10301                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10302                    if (libPkg == null) {
10303                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10304                                "Package " + packageName + " requires unavailable static shared"
10305                                        + " library; failing!");
10306                    }
10307
10308                    String expectedCertDigest = requiredCertDigests[i];
10309                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10310                                libPkg.mSignatures[0]);
10311                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10312                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10313                                "Package " + packageName + " requires differently signed" +
10314                                        " static shared library; failing!");
10315                    }
10316                }
10317
10318                if (outUsedLibraries == null) {
10319                    outUsedLibraries = new ArraySet<>();
10320                }
10321                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10322            }
10323        }
10324        return outUsedLibraries;
10325    }
10326
10327    private static boolean hasString(List<String> list, List<String> which) {
10328        if (list == null) {
10329            return false;
10330        }
10331        for (int i=list.size()-1; i>=0; i--) {
10332            for (int j=which.size()-1; j>=0; j--) {
10333                if (which.get(j).equals(list.get(i))) {
10334                    return true;
10335                }
10336            }
10337        }
10338        return false;
10339    }
10340
10341    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10342            PackageParser.Package changingPkg) {
10343        ArrayList<PackageParser.Package> res = null;
10344        for (PackageParser.Package pkg : mPackages.values()) {
10345            if (changingPkg != null
10346                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10347                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10348                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10349                            changingPkg.staticSharedLibName)) {
10350                return null;
10351            }
10352            if (res == null) {
10353                res = new ArrayList<>();
10354            }
10355            res.add(pkg);
10356            try {
10357                updateSharedLibrariesLPr(pkg, changingPkg);
10358            } catch (PackageManagerException e) {
10359                // If a system app update or an app and a required lib missing we
10360                // delete the package and for updated system apps keep the data as
10361                // it is better for the user to reinstall than to be in an limbo
10362                // state. Also libs disappearing under an app should never happen
10363                // - just in case.
10364                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10365                    final int flags = pkg.isUpdatedSystemApp()
10366                            ? PackageManager.DELETE_KEEP_DATA : 0;
10367                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10368                            flags , null, true, null);
10369                }
10370                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10371            }
10372        }
10373        return res;
10374    }
10375
10376    /**
10377     * Derive the value of the {@code cpuAbiOverride} based on the provided
10378     * value and an optional stored value from the package settings.
10379     */
10380    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10381        String cpuAbiOverride = null;
10382
10383        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10384            cpuAbiOverride = null;
10385        } else if (abiOverride != null) {
10386            cpuAbiOverride = abiOverride;
10387        } else if (settings != null) {
10388            cpuAbiOverride = settings.cpuAbiOverrideString;
10389        }
10390
10391        return cpuAbiOverride;
10392    }
10393
10394    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10395            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10396                    throws PackageManagerException {
10397        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10398        // If the package has children and this is the first dive in the function
10399        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10400        // whether all packages (parent and children) would be successfully scanned
10401        // before the actual scan since scanning mutates internal state and we want
10402        // to atomically install the package and its children.
10403        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10404            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10405                scanFlags |= SCAN_CHECK_ONLY;
10406            }
10407        } else {
10408            scanFlags &= ~SCAN_CHECK_ONLY;
10409        }
10410
10411        final PackageParser.Package scannedPkg;
10412        try {
10413            // Scan the parent
10414            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10415            // Scan the children
10416            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10417            for (int i = 0; i < childCount; i++) {
10418                PackageParser.Package childPkg = pkg.childPackages.get(i);
10419                scanPackageLI(childPkg, policyFlags,
10420                        scanFlags, currentTime, user);
10421            }
10422        } finally {
10423            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10424        }
10425
10426        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10427            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10428        }
10429
10430        return scannedPkg;
10431    }
10432
10433    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10434            int scanFlags, long currentTime, @Nullable UserHandle user)
10435                    throws PackageManagerException {
10436        boolean success = false;
10437        try {
10438            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10439                    currentTime, user);
10440            success = true;
10441            return res;
10442        } finally {
10443            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10444                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10445                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10446                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10447                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10448            }
10449        }
10450    }
10451
10452    /**
10453     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10454     */
10455    private static boolean apkHasCode(String fileName) {
10456        StrictJarFile jarFile = null;
10457        try {
10458            jarFile = new StrictJarFile(fileName,
10459                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10460            return jarFile.findEntry("classes.dex") != null;
10461        } catch (IOException ignore) {
10462        } finally {
10463            try {
10464                if (jarFile != null) {
10465                    jarFile.close();
10466                }
10467            } catch (IOException ignore) {}
10468        }
10469        return false;
10470    }
10471
10472    /**
10473     * Enforces code policy for the package. This ensures that if an APK has
10474     * declared hasCode="true" in its manifest that the APK actually contains
10475     * code.
10476     *
10477     * @throws PackageManagerException If bytecode could not be found when it should exist
10478     */
10479    private static void assertCodePolicy(PackageParser.Package pkg)
10480            throws PackageManagerException {
10481        final boolean shouldHaveCode =
10482                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10483        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10484            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10485                    "Package " + pkg.baseCodePath + " code is missing");
10486        }
10487
10488        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10489            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10490                final boolean splitShouldHaveCode =
10491                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10492                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10493                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10494                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10495                }
10496            }
10497        }
10498    }
10499
10500    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10501            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10502                    throws PackageManagerException {
10503        if (DEBUG_PACKAGE_SCANNING) {
10504            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10505                Log.d(TAG, "Scanning package " + pkg.packageName);
10506        }
10507
10508        applyPolicy(pkg, policyFlags);
10509
10510        assertPackageIsValid(pkg, policyFlags, scanFlags);
10511
10512        // Initialize package source and resource directories
10513        final File scanFile = new File(pkg.codePath);
10514        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10515        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10516
10517        SharedUserSetting suid = null;
10518        PackageSetting pkgSetting = null;
10519
10520        // Getting the package setting may have a side-effect, so if we
10521        // are only checking if scan would succeed, stash a copy of the
10522        // old setting to restore at the end.
10523        PackageSetting nonMutatedPs = null;
10524
10525        // We keep references to the derived CPU Abis from settings in oder to reuse
10526        // them in the case where we're not upgrading or booting for the first time.
10527        String primaryCpuAbiFromSettings = null;
10528        String secondaryCpuAbiFromSettings = null;
10529
10530        // writer
10531        synchronized (mPackages) {
10532            if (pkg.mSharedUserId != null) {
10533                // SIDE EFFECTS; may potentially allocate a new shared user
10534                suid = mSettings.getSharedUserLPw(
10535                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10536                if (DEBUG_PACKAGE_SCANNING) {
10537                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10538                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10539                                + "): packages=" + suid.packages);
10540                }
10541            }
10542
10543            // Check if we are renaming from an original package name.
10544            PackageSetting origPackage = null;
10545            String realName = null;
10546            if (pkg.mOriginalPackages != null) {
10547                // This package may need to be renamed to a previously
10548                // installed name.  Let's check on that...
10549                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10550                if (pkg.mOriginalPackages.contains(renamed)) {
10551                    // This package had originally been installed as the
10552                    // original name, and we have already taken care of
10553                    // transitioning to the new one.  Just update the new
10554                    // one to continue using the old name.
10555                    realName = pkg.mRealPackage;
10556                    if (!pkg.packageName.equals(renamed)) {
10557                        // Callers into this function may have already taken
10558                        // care of renaming the package; only do it here if
10559                        // it is not already done.
10560                        pkg.setPackageName(renamed);
10561                    }
10562                } else {
10563                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10564                        if ((origPackage = mSettings.getPackageLPr(
10565                                pkg.mOriginalPackages.get(i))) != null) {
10566                            // We do have the package already installed under its
10567                            // original name...  should we use it?
10568                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10569                                // New package is not compatible with original.
10570                                origPackage = null;
10571                                continue;
10572                            } else if (origPackage.sharedUser != null) {
10573                                // Make sure uid is compatible between packages.
10574                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10575                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10576                                            + " to " + pkg.packageName + ": old uid "
10577                                            + origPackage.sharedUser.name
10578                                            + " differs from " + pkg.mSharedUserId);
10579                                    origPackage = null;
10580                                    continue;
10581                                }
10582                                // TODO: Add case when shared user id is added [b/28144775]
10583                            } else {
10584                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10585                                        + pkg.packageName + " to old name " + origPackage.name);
10586                            }
10587                            break;
10588                        }
10589                    }
10590                }
10591            }
10592
10593            if (mTransferedPackages.contains(pkg.packageName)) {
10594                Slog.w(TAG, "Package " + pkg.packageName
10595                        + " was transferred to another, but its .apk remains");
10596            }
10597
10598            // See comments in nonMutatedPs declaration
10599            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10600                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10601                if (foundPs != null) {
10602                    nonMutatedPs = new PackageSetting(foundPs);
10603                }
10604            }
10605
10606            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10607                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10608                if (foundPs != null) {
10609                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10610                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10611                }
10612            }
10613
10614            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10615            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10616                PackageManagerService.reportSettingsProblem(Log.WARN,
10617                        "Package " + pkg.packageName + " shared user changed from "
10618                                + (pkgSetting.sharedUser != null
10619                                        ? pkgSetting.sharedUser.name : "<nothing>")
10620                                + " to "
10621                                + (suid != null ? suid.name : "<nothing>")
10622                                + "; replacing with new");
10623                pkgSetting = null;
10624            }
10625            final PackageSetting oldPkgSetting =
10626                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10627            final PackageSetting disabledPkgSetting =
10628                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10629
10630            String[] usesStaticLibraries = null;
10631            if (pkg.usesStaticLibraries != null) {
10632                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10633                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10634            }
10635
10636            if (pkgSetting == null) {
10637                final String parentPackageName = (pkg.parentPackage != null)
10638                        ? pkg.parentPackage.packageName : null;
10639                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10640                // REMOVE SharedUserSetting from method; update in a separate call
10641                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10642                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10643                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10644                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10645                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10646                        true /*allowInstall*/, instantApp, parentPackageName,
10647                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10648                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10649                // SIDE EFFECTS; updates system state; move elsewhere
10650                if (origPackage != null) {
10651                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10652                }
10653                mSettings.addUserToSettingLPw(pkgSetting);
10654            } else {
10655                // REMOVE SharedUserSetting from method; update in a separate call.
10656                //
10657                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10658                // secondaryCpuAbi are not known at this point so we always update them
10659                // to null here, only to reset them at a later point.
10660                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10661                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10662                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10663                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10664                        UserManagerService.getInstance(), usesStaticLibraries,
10665                        pkg.usesStaticLibrariesVersions);
10666            }
10667            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10668            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10669
10670            // SIDE EFFECTS; modifies system state; move elsewhere
10671            if (pkgSetting.origPackage != null) {
10672                // If we are first transitioning from an original package,
10673                // fix up the new package's name now.  We need to do this after
10674                // looking up the package under its new name, so getPackageLP
10675                // can take care of fiddling things correctly.
10676                pkg.setPackageName(origPackage.name);
10677
10678                // File a report about this.
10679                String msg = "New package " + pkgSetting.realName
10680                        + " renamed to replace old package " + pkgSetting.name;
10681                reportSettingsProblem(Log.WARN, msg);
10682
10683                // Make a note of it.
10684                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10685                    mTransferedPackages.add(origPackage.name);
10686                }
10687
10688                // No longer need to retain this.
10689                pkgSetting.origPackage = null;
10690            }
10691
10692            // SIDE EFFECTS; modifies system state; move elsewhere
10693            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10694                // Make a note of it.
10695                mTransferedPackages.add(pkg.packageName);
10696            }
10697
10698            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10699                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10700            }
10701
10702            if ((scanFlags & SCAN_BOOTING) == 0
10703                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10704                // Check all shared libraries and map to their actual file path.
10705                // We only do this here for apps not on a system dir, because those
10706                // are the only ones that can fail an install due to this.  We
10707                // will take care of the system apps by updating all of their
10708                // library paths after the scan is done. Also during the initial
10709                // scan don't update any libs as we do this wholesale after all
10710                // apps are scanned to avoid dependency based scanning.
10711                updateSharedLibrariesLPr(pkg, null);
10712            }
10713
10714            if (mFoundPolicyFile) {
10715                SELinuxMMAC.assignSeInfoValue(pkg);
10716            }
10717            pkg.applicationInfo.uid = pkgSetting.appId;
10718            pkg.mExtras = pkgSetting;
10719
10720
10721            // Static shared libs have same package with different versions where
10722            // we internally use a synthetic package name to allow multiple versions
10723            // of the same package, therefore we need to compare signatures against
10724            // the package setting for the latest library version.
10725            PackageSetting signatureCheckPs = pkgSetting;
10726            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10727                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10728                if (libraryEntry != null) {
10729                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10730                }
10731            }
10732
10733            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10734                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10735                    // We just determined the app is signed correctly, so bring
10736                    // over the latest parsed certs.
10737                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10738                } else {
10739                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10740                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10741                                "Package " + pkg.packageName + " upgrade keys do not match the "
10742                                + "previously installed version");
10743                    } else {
10744                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10745                        String msg = "System package " + pkg.packageName
10746                                + " signature changed; retaining data.";
10747                        reportSettingsProblem(Log.WARN, msg);
10748                    }
10749                }
10750            } else {
10751                try {
10752                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10753                    verifySignaturesLP(signatureCheckPs, pkg);
10754                    // We just determined the app is signed correctly, so bring
10755                    // over the latest parsed certs.
10756                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10757                } catch (PackageManagerException e) {
10758                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10759                        throw e;
10760                    }
10761                    // The signature has changed, but this package is in the system
10762                    // image...  let's recover!
10763                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10764                    // However...  if this package is part of a shared user, but it
10765                    // doesn't match the signature of the shared user, let's fail.
10766                    // What this means is that you can't change the signatures
10767                    // associated with an overall shared user, which doesn't seem all
10768                    // that unreasonable.
10769                    if (signatureCheckPs.sharedUser != null) {
10770                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10771                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10772                            throw new PackageManagerException(
10773                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10774                                    "Signature mismatch for shared user: "
10775                                            + pkgSetting.sharedUser);
10776                        }
10777                    }
10778                    // File a report about this.
10779                    String msg = "System package " + pkg.packageName
10780                            + " signature changed; retaining data.";
10781                    reportSettingsProblem(Log.WARN, msg);
10782                }
10783            }
10784
10785            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10786                // This package wants to adopt ownership of permissions from
10787                // another package.
10788                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10789                    final String origName = pkg.mAdoptPermissions.get(i);
10790                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10791                    if (orig != null) {
10792                        if (verifyPackageUpdateLPr(orig, pkg)) {
10793                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10794                                    + pkg.packageName);
10795                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10796                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10797                        }
10798                    }
10799                }
10800            }
10801        }
10802
10803        pkg.applicationInfo.processName = fixProcessName(
10804                pkg.applicationInfo.packageName,
10805                pkg.applicationInfo.processName);
10806
10807        if (pkg != mPlatformPackage) {
10808            // Get all of our default paths setup
10809            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10810        }
10811
10812        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10813
10814        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10815            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10816                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10817                final boolean extractNativeLibs = !pkg.isLibrary();
10818                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10819                        mAppLib32InstallDir);
10820                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10821
10822                // Some system apps still use directory structure for native libraries
10823                // in which case we might end up not detecting abi solely based on apk
10824                // structure. Try to detect abi based on directory structure.
10825                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10826                        pkg.applicationInfo.primaryCpuAbi == null) {
10827                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10828                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10829                }
10830            } else {
10831                // This is not a first boot or an upgrade, don't bother deriving the
10832                // ABI during the scan. Instead, trust the value that was stored in the
10833                // package setting.
10834                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10835                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10836
10837                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10838
10839                if (DEBUG_ABI_SELECTION) {
10840                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10841                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10842                        pkg.applicationInfo.secondaryCpuAbi);
10843                }
10844            }
10845        } else {
10846            if ((scanFlags & SCAN_MOVE) != 0) {
10847                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10848                // but we already have this packages package info in the PackageSetting. We just
10849                // use that and derive the native library path based on the new codepath.
10850                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10851                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10852            }
10853
10854            // Set native library paths again. For moves, the path will be updated based on the
10855            // ABIs we've determined above. For non-moves, the path will be updated based on the
10856            // ABIs we determined during compilation, but the path will depend on the final
10857            // package path (after the rename away from the stage path).
10858            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10859        }
10860
10861        // This is a special case for the "system" package, where the ABI is
10862        // dictated by the zygote configuration (and init.rc). We should keep track
10863        // of this ABI so that we can deal with "normal" applications that run under
10864        // the same UID correctly.
10865        if (mPlatformPackage == pkg) {
10866            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10867                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10868        }
10869
10870        // If there's a mismatch between the abi-override in the package setting
10871        // and the abiOverride specified for the install. Warn about this because we
10872        // would've already compiled the app without taking the package setting into
10873        // account.
10874        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10875            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10876                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10877                        " for package " + pkg.packageName);
10878            }
10879        }
10880
10881        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10882        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10883        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10884
10885        // Copy the derived override back to the parsed package, so that we can
10886        // update the package settings accordingly.
10887        pkg.cpuAbiOverride = cpuAbiOverride;
10888
10889        if (DEBUG_ABI_SELECTION) {
10890            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10891                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10892                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10893        }
10894
10895        // Push the derived path down into PackageSettings so we know what to
10896        // clean up at uninstall time.
10897        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10898
10899        if (DEBUG_ABI_SELECTION) {
10900            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10901                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10902                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10903        }
10904
10905        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10906        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10907            // We don't do this here during boot because we can do it all
10908            // at once after scanning all existing packages.
10909            //
10910            // We also do this *before* we perform dexopt on this package, so that
10911            // we can avoid redundant dexopts, and also to make sure we've got the
10912            // code and package path correct.
10913            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10914        }
10915
10916        if (mFactoryTest && pkg.requestedPermissions.contains(
10917                android.Manifest.permission.FACTORY_TEST)) {
10918            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10919        }
10920
10921        if (isSystemApp(pkg)) {
10922            pkgSetting.isOrphaned = true;
10923        }
10924
10925        // Take care of first install / last update times.
10926        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10927        if (currentTime != 0) {
10928            if (pkgSetting.firstInstallTime == 0) {
10929                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10930            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10931                pkgSetting.lastUpdateTime = currentTime;
10932            }
10933        } else if (pkgSetting.firstInstallTime == 0) {
10934            // We need *something*.  Take time time stamp of the file.
10935            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10936        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10937            if (scanFileTime != pkgSetting.timeStamp) {
10938                // A package on the system image has changed; consider this
10939                // to be an update.
10940                pkgSetting.lastUpdateTime = scanFileTime;
10941            }
10942        }
10943        pkgSetting.setTimeStamp(scanFileTime);
10944
10945        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10946            if (nonMutatedPs != null) {
10947                synchronized (mPackages) {
10948                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10949                }
10950            }
10951        } else {
10952            final int userId = user == null ? 0 : user.getIdentifier();
10953            // Modify state for the given package setting
10954            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10955                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10956            if (pkgSetting.getInstantApp(userId)) {
10957                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10958            }
10959        }
10960        return pkg;
10961    }
10962
10963    /**
10964     * Applies policy to the parsed package based upon the given policy flags.
10965     * Ensures the package is in a good state.
10966     * <p>
10967     * Implementation detail: This method must NOT have any side effect. It would
10968     * ideally be static, but, it requires locks to read system state.
10969     */
10970    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10971        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10972            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10973            if (pkg.applicationInfo.isDirectBootAware()) {
10974                // we're direct boot aware; set for all components
10975                for (PackageParser.Service s : pkg.services) {
10976                    s.info.encryptionAware = s.info.directBootAware = true;
10977                }
10978                for (PackageParser.Provider p : pkg.providers) {
10979                    p.info.encryptionAware = p.info.directBootAware = true;
10980                }
10981                for (PackageParser.Activity a : pkg.activities) {
10982                    a.info.encryptionAware = a.info.directBootAware = true;
10983                }
10984                for (PackageParser.Activity r : pkg.receivers) {
10985                    r.info.encryptionAware = r.info.directBootAware = true;
10986                }
10987            }
10988            if (compressedFileExists(pkg.baseCodePath)) {
10989                pkg.isStub = true;
10990            }
10991        } else {
10992            // Only allow system apps to be flagged as core apps.
10993            pkg.coreApp = false;
10994            // clear flags not applicable to regular apps
10995            pkg.applicationInfo.privateFlags &=
10996                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10997            pkg.applicationInfo.privateFlags &=
10998                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10999        }
11000        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11001
11002        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11003            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11004        }
11005
11006        if (!isSystemApp(pkg)) {
11007            // Only system apps can use these features.
11008            pkg.mOriginalPackages = null;
11009            pkg.mRealPackage = null;
11010            pkg.mAdoptPermissions = null;
11011        }
11012    }
11013
11014    /**
11015     * Asserts the parsed package is valid according to the given policy. If the
11016     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11017     * <p>
11018     * Implementation detail: This method must NOT have any side effects. It would
11019     * ideally be static, but, it requires locks to read system state.
11020     *
11021     * @throws PackageManagerException If the package fails any of the validation checks
11022     */
11023    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11024            throws PackageManagerException {
11025        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11026            assertCodePolicy(pkg);
11027        }
11028
11029        if (pkg.applicationInfo.getCodePath() == null ||
11030                pkg.applicationInfo.getResourcePath() == null) {
11031            // Bail out. The resource and code paths haven't been set.
11032            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11033                    "Code and resource paths haven't been set correctly");
11034        }
11035
11036        // Make sure we're not adding any bogus keyset info
11037        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11038        ksms.assertScannedPackageValid(pkg);
11039
11040        synchronized (mPackages) {
11041            // The special "android" package can only be defined once
11042            if (pkg.packageName.equals("android")) {
11043                if (mAndroidApplication != null) {
11044                    Slog.w(TAG, "*************************************************");
11045                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11046                    Slog.w(TAG, " codePath=" + pkg.codePath);
11047                    Slog.w(TAG, "*************************************************");
11048                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11049                            "Core android package being redefined.  Skipping.");
11050                }
11051            }
11052
11053            // A package name must be unique; don't allow duplicates
11054            if (mPackages.containsKey(pkg.packageName)) {
11055                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11056                        "Application package " + pkg.packageName
11057                        + " already installed.  Skipping duplicate.");
11058            }
11059
11060            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11061                // Static libs have a synthetic package name containing the version
11062                // but we still want the base name to be unique.
11063                if (mPackages.containsKey(pkg.manifestPackageName)) {
11064                    throw new PackageManagerException(
11065                            "Duplicate static shared lib provider package");
11066                }
11067
11068                // Static shared libraries should have at least O target SDK
11069                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11070                    throw new PackageManagerException(
11071                            "Packages declaring static-shared libs must target O SDK or higher");
11072                }
11073
11074                // Package declaring static a shared lib cannot be instant apps
11075                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11076                    throw new PackageManagerException(
11077                            "Packages declaring static-shared libs cannot be instant apps");
11078                }
11079
11080                // Package declaring static a shared lib cannot be renamed since the package
11081                // name is synthetic and apps can't code around package manager internals.
11082                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11083                    throw new PackageManagerException(
11084                            "Packages declaring static-shared libs cannot be renamed");
11085                }
11086
11087                // Package declaring static a shared lib cannot declare child packages
11088                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11089                    throw new PackageManagerException(
11090                            "Packages declaring static-shared libs cannot have child packages");
11091                }
11092
11093                // Package declaring static a shared lib cannot declare dynamic libs
11094                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11095                    throw new PackageManagerException(
11096                            "Packages declaring static-shared libs cannot declare dynamic libs");
11097                }
11098
11099                // Package declaring static a shared lib cannot declare shared users
11100                if (pkg.mSharedUserId != null) {
11101                    throw new PackageManagerException(
11102                            "Packages declaring static-shared libs cannot declare shared users");
11103                }
11104
11105                // Static shared libs cannot declare activities
11106                if (!pkg.activities.isEmpty()) {
11107                    throw new PackageManagerException(
11108                            "Static shared libs cannot declare activities");
11109                }
11110
11111                // Static shared libs cannot declare services
11112                if (!pkg.services.isEmpty()) {
11113                    throw new PackageManagerException(
11114                            "Static shared libs cannot declare services");
11115                }
11116
11117                // Static shared libs cannot declare providers
11118                if (!pkg.providers.isEmpty()) {
11119                    throw new PackageManagerException(
11120                            "Static shared libs cannot declare content providers");
11121                }
11122
11123                // Static shared libs cannot declare receivers
11124                if (!pkg.receivers.isEmpty()) {
11125                    throw new PackageManagerException(
11126                            "Static shared libs cannot declare broadcast receivers");
11127                }
11128
11129                // Static shared libs cannot declare permission groups
11130                if (!pkg.permissionGroups.isEmpty()) {
11131                    throw new PackageManagerException(
11132                            "Static shared libs cannot declare permission groups");
11133                }
11134
11135                // Static shared libs cannot declare permissions
11136                if (!pkg.permissions.isEmpty()) {
11137                    throw new PackageManagerException(
11138                            "Static shared libs cannot declare permissions");
11139                }
11140
11141                // Static shared libs cannot declare protected broadcasts
11142                if (pkg.protectedBroadcasts != null) {
11143                    throw new PackageManagerException(
11144                            "Static shared libs cannot declare protected broadcasts");
11145                }
11146
11147                // Static shared libs cannot be overlay targets
11148                if (pkg.mOverlayTarget != null) {
11149                    throw new PackageManagerException(
11150                            "Static shared libs cannot be overlay targets");
11151                }
11152
11153                // The version codes must be ordered as lib versions
11154                int minVersionCode = Integer.MIN_VALUE;
11155                int maxVersionCode = Integer.MAX_VALUE;
11156
11157                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11158                        pkg.staticSharedLibName);
11159                if (versionedLib != null) {
11160                    final int versionCount = versionedLib.size();
11161                    for (int i = 0; i < versionCount; i++) {
11162                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11163                        final int libVersionCode = libInfo.getDeclaringPackage()
11164                                .getVersionCode();
11165                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11166                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11167                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11168                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11169                        } else {
11170                            minVersionCode = maxVersionCode = libVersionCode;
11171                            break;
11172                        }
11173                    }
11174                }
11175                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11176                    throw new PackageManagerException("Static shared"
11177                            + " lib version codes must be ordered as lib versions");
11178                }
11179            }
11180
11181            // Only privileged apps and updated privileged apps can add child packages.
11182            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11183                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11184                    throw new PackageManagerException("Only privileged apps can add child "
11185                            + "packages. Ignoring package " + pkg.packageName);
11186                }
11187                final int childCount = pkg.childPackages.size();
11188                for (int i = 0; i < childCount; i++) {
11189                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11190                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11191                            childPkg.packageName)) {
11192                        throw new PackageManagerException("Can't override child of "
11193                                + "another disabled app. Ignoring package " + pkg.packageName);
11194                    }
11195                }
11196            }
11197
11198            // If we're only installing presumed-existing packages, require that the
11199            // scanned APK is both already known and at the path previously established
11200            // for it.  Previously unknown packages we pick up normally, but if we have an
11201            // a priori expectation about this package's install presence, enforce it.
11202            // With a singular exception for new system packages. When an OTA contains
11203            // a new system package, we allow the codepath to change from a system location
11204            // to the user-installed location. If we don't allow this change, any newer,
11205            // user-installed version of the application will be ignored.
11206            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11207                if (mExpectingBetter.containsKey(pkg.packageName)) {
11208                    logCriticalInfo(Log.WARN,
11209                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11210                } else {
11211                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11212                    if (known != null) {
11213                        if (DEBUG_PACKAGE_SCANNING) {
11214                            Log.d(TAG, "Examining " + pkg.codePath
11215                                    + " and requiring known paths " + known.codePathString
11216                                    + " & " + known.resourcePathString);
11217                        }
11218                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11219                                || !pkg.applicationInfo.getResourcePath().equals(
11220                                        known.resourcePathString)) {
11221                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11222                                    "Application package " + pkg.packageName
11223                                    + " found at " + pkg.applicationInfo.getCodePath()
11224                                    + " but expected at " + known.codePathString
11225                                    + "; ignoring.");
11226                        }
11227                    }
11228                }
11229            }
11230
11231            // Verify that this new package doesn't have any content providers
11232            // that conflict with existing packages.  Only do this if the
11233            // package isn't already installed, since we don't want to break
11234            // things that are installed.
11235            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11236                final int N = pkg.providers.size();
11237                int i;
11238                for (i=0; i<N; i++) {
11239                    PackageParser.Provider p = pkg.providers.get(i);
11240                    if (p.info.authority != null) {
11241                        String names[] = p.info.authority.split(";");
11242                        for (int j = 0; j < names.length; j++) {
11243                            if (mProvidersByAuthority.containsKey(names[j])) {
11244                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11245                                final String otherPackageName =
11246                                        ((other != null && other.getComponentName() != null) ?
11247                                                other.getComponentName().getPackageName() : "?");
11248                                throw new PackageManagerException(
11249                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11250                                        "Can't install because provider name " + names[j]
11251                                                + " (in package " + pkg.applicationInfo.packageName
11252                                                + ") is already used by " + otherPackageName);
11253                            }
11254                        }
11255                    }
11256                }
11257            }
11258        }
11259    }
11260
11261    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11262            int type, String declaringPackageName, int declaringVersionCode) {
11263        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11264        if (versionedLib == null) {
11265            versionedLib = new SparseArray<>();
11266            mSharedLibraries.put(name, versionedLib);
11267            if (type == SharedLibraryInfo.TYPE_STATIC) {
11268                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11269            }
11270        } else if (versionedLib.indexOfKey(version) >= 0) {
11271            return false;
11272        }
11273        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11274                version, type, declaringPackageName, declaringVersionCode);
11275        versionedLib.put(version, libEntry);
11276        return true;
11277    }
11278
11279    private boolean removeSharedLibraryLPw(String name, int version) {
11280        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11281        if (versionedLib == null) {
11282            return false;
11283        }
11284        final int libIdx = versionedLib.indexOfKey(version);
11285        if (libIdx < 0) {
11286            return false;
11287        }
11288        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11289        versionedLib.remove(version);
11290        if (versionedLib.size() <= 0) {
11291            mSharedLibraries.remove(name);
11292            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11293                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11294                        .getPackageName());
11295            }
11296        }
11297        return true;
11298    }
11299
11300    /**
11301     * Adds a scanned package to the system. When this method is finished, the package will
11302     * be available for query, resolution, etc...
11303     */
11304    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11305            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11306        final String pkgName = pkg.packageName;
11307        if (mCustomResolverComponentName != null &&
11308                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11309            setUpCustomResolverActivity(pkg);
11310        }
11311
11312        if (pkg.packageName.equals("android")) {
11313            synchronized (mPackages) {
11314                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11315                    // Set up information for our fall-back user intent resolution activity.
11316                    mPlatformPackage = pkg;
11317                    pkg.mVersionCode = mSdkVersion;
11318                    mAndroidApplication = pkg.applicationInfo;
11319                    if (!mResolverReplaced) {
11320                        mResolveActivity.applicationInfo = mAndroidApplication;
11321                        mResolveActivity.name = ResolverActivity.class.getName();
11322                        mResolveActivity.packageName = mAndroidApplication.packageName;
11323                        mResolveActivity.processName = "system:ui";
11324                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11325                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11326                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11327                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11328                        mResolveActivity.exported = true;
11329                        mResolveActivity.enabled = true;
11330                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11331                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11332                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11333                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11334                                | ActivityInfo.CONFIG_ORIENTATION
11335                                | ActivityInfo.CONFIG_KEYBOARD
11336                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11337                        mResolveInfo.activityInfo = mResolveActivity;
11338                        mResolveInfo.priority = 0;
11339                        mResolveInfo.preferredOrder = 0;
11340                        mResolveInfo.match = 0;
11341                        mResolveComponentName = new ComponentName(
11342                                mAndroidApplication.packageName, mResolveActivity.name);
11343                    }
11344                }
11345            }
11346        }
11347
11348        ArrayList<PackageParser.Package> clientLibPkgs = null;
11349        // writer
11350        synchronized (mPackages) {
11351            boolean hasStaticSharedLibs = false;
11352
11353            // Any app can add new static shared libraries
11354            if (pkg.staticSharedLibName != null) {
11355                // Static shared libs don't allow renaming as they have synthetic package
11356                // names to allow install of multiple versions, so use name from manifest.
11357                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11358                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11359                        pkg.manifestPackageName, pkg.mVersionCode)) {
11360                    hasStaticSharedLibs = true;
11361                } else {
11362                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11363                                + pkg.staticSharedLibName + " already exists; skipping");
11364                }
11365                // Static shared libs cannot be updated once installed since they
11366                // use synthetic package name which includes the version code, so
11367                // not need to update other packages's shared lib dependencies.
11368            }
11369
11370            if (!hasStaticSharedLibs
11371                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11372                // Only system apps can add new dynamic shared libraries.
11373                if (pkg.libraryNames != null) {
11374                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11375                        String name = pkg.libraryNames.get(i);
11376                        boolean allowed = false;
11377                        if (pkg.isUpdatedSystemApp()) {
11378                            // New library entries can only be added through the
11379                            // system image.  This is important to get rid of a lot
11380                            // of nasty edge cases: for example if we allowed a non-
11381                            // system update of the app to add a library, then uninstalling
11382                            // the update would make the library go away, and assumptions
11383                            // we made such as through app install filtering would now
11384                            // have allowed apps on the device which aren't compatible
11385                            // with it.  Better to just have the restriction here, be
11386                            // conservative, and create many fewer cases that can negatively
11387                            // impact the user experience.
11388                            final PackageSetting sysPs = mSettings
11389                                    .getDisabledSystemPkgLPr(pkg.packageName);
11390                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11391                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11392                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11393                                        allowed = true;
11394                                        break;
11395                                    }
11396                                }
11397                            }
11398                        } else {
11399                            allowed = true;
11400                        }
11401                        if (allowed) {
11402                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11403                                    SharedLibraryInfo.VERSION_UNDEFINED,
11404                                    SharedLibraryInfo.TYPE_DYNAMIC,
11405                                    pkg.packageName, pkg.mVersionCode)) {
11406                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11407                                        + name + " already exists; skipping");
11408                            }
11409                        } else {
11410                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11411                                    + name + " that is not declared on system image; skipping");
11412                        }
11413                    }
11414
11415                    if ((scanFlags & SCAN_BOOTING) == 0) {
11416                        // If we are not booting, we need to update any applications
11417                        // that are clients of our shared library.  If we are booting,
11418                        // this will all be done once the scan is complete.
11419                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11420                    }
11421                }
11422            }
11423        }
11424
11425        if ((scanFlags & SCAN_BOOTING) != 0) {
11426            // No apps can run during boot scan, so they don't need to be frozen
11427        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11428            // Caller asked to not kill app, so it's probably not frozen
11429        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11430            // Caller asked us to ignore frozen check for some reason; they
11431            // probably didn't know the package name
11432        } else {
11433            // We're doing major surgery on this package, so it better be frozen
11434            // right now to keep it from launching
11435            checkPackageFrozen(pkgName);
11436        }
11437
11438        // Also need to kill any apps that are dependent on the library.
11439        if (clientLibPkgs != null) {
11440            for (int i=0; i<clientLibPkgs.size(); i++) {
11441                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11442                killApplication(clientPkg.applicationInfo.packageName,
11443                        clientPkg.applicationInfo.uid, "update lib");
11444            }
11445        }
11446
11447        // writer
11448        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11449
11450        synchronized (mPackages) {
11451            // We don't expect installation to fail beyond this point
11452
11453            // Add the new setting to mSettings
11454            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11455            // Add the new setting to mPackages
11456            mPackages.put(pkg.applicationInfo.packageName, pkg);
11457            // Make sure we don't accidentally delete its data.
11458            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11459            while (iter.hasNext()) {
11460                PackageCleanItem item = iter.next();
11461                if (pkgName.equals(item.packageName)) {
11462                    iter.remove();
11463                }
11464            }
11465
11466            // Add the package's KeySets to the global KeySetManagerService
11467            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11468            ksms.addScannedPackageLPw(pkg);
11469
11470            int N = pkg.providers.size();
11471            StringBuilder r = null;
11472            int i;
11473            for (i=0; i<N; i++) {
11474                PackageParser.Provider p = pkg.providers.get(i);
11475                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11476                        p.info.processName);
11477                mProviders.addProvider(p);
11478                p.syncable = p.info.isSyncable;
11479                if (p.info.authority != null) {
11480                    String names[] = p.info.authority.split(";");
11481                    p.info.authority = null;
11482                    for (int j = 0; j < names.length; j++) {
11483                        if (j == 1 && p.syncable) {
11484                            // We only want the first authority for a provider to possibly be
11485                            // syncable, so if we already added this provider using a different
11486                            // authority clear the syncable flag. We copy the provider before
11487                            // changing it because the mProviders object contains a reference
11488                            // to a provider that we don't want to change.
11489                            // Only do this for the second authority since the resulting provider
11490                            // object can be the same for all future authorities for this provider.
11491                            p = new PackageParser.Provider(p);
11492                            p.syncable = false;
11493                        }
11494                        if (!mProvidersByAuthority.containsKey(names[j])) {
11495                            mProvidersByAuthority.put(names[j], p);
11496                            if (p.info.authority == null) {
11497                                p.info.authority = names[j];
11498                            } else {
11499                                p.info.authority = p.info.authority + ";" + names[j];
11500                            }
11501                            if (DEBUG_PACKAGE_SCANNING) {
11502                                if (chatty)
11503                                    Log.d(TAG, "Registered content provider: " + names[j]
11504                                            + ", className = " + p.info.name + ", isSyncable = "
11505                                            + p.info.isSyncable);
11506                            }
11507                        } else {
11508                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11509                            Slog.w(TAG, "Skipping provider name " + names[j] +
11510                                    " (in package " + pkg.applicationInfo.packageName +
11511                                    "): name already used by "
11512                                    + ((other != null && other.getComponentName() != null)
11513                                            ? other.getComponentName().getPackageName() : "?"));
11514                        }
11515                    }
11516                }
11517                if (chatty) {
11518                    if (r == null) {
11519                        r = new StringBuilder(256);
11520                    } else {
11521                        r.append(' ');
11522                    }
11523                    r.append(p.info.name);
11524                }
11525            }
11526            if (r != null) {
11527                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11528            }
11529
11530            N = pkg.services.size();
11531            r = null;
11532            for (i=0; i<N; i++) {
11533                PackageParser.Service s = pkg.services.get(i);
11534                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11535                        s.info.processName);
11536                mServices.addService(s);
11537                if (chatty) {
11538                    if (r == null) {
11539                        r = new StringBuilder(256);
11540                    } else {
11541                        r.append(' ');
11542                    }
11543                    r.append(s.info.name);
11544                }
11545            }
11546            if (r != null) {
11547                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11548            }
11549
11550            N = pkg.receivers.size();
11551            r = null;
11552            for (i=0; i<N; i++) {
11553                PackageParser.Activity a = pkg.receivers.get(i);
11554                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11555                        a.info.processName);
11556                mReceivers.addActivity(a, "receiver");
11557                if (chatty) {
11558                    if (r == null) {
11559                        r = new StringBuilder(256);
11560                    } else {
11561                        r.append(' ');
11562                    }
11563                    r.append(a.info.name);
11564                }
11565            }
11566            if (r != null) {
11567                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11568            }
11569
11570            N = pkg.activities.size();
11571            r = null;
11572            for (i=0; i<N; i++) {
11573                PackageParser.Activity a = pkg.activities.get(i);
11574                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11575                        a.info.processName);
11576                mActivities.addActivity(a, "activity");
11577                if (chatty) {
11578                    if (r == null) {
11579                        r = new StringBuilder(256);
11580                    } else {
11581                        r.append(' ');
11582                    }
11583                    r.append(a.info.name);
11584                }
11585            }
11586            if (r != null) {
11587                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11588            }
11589
11590            N = pkg.permissionGroups.size();
11591            r = null;
11592            for (i=0; i<N; i++) {
11593                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11594                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11595                final String curPackageName = cur == null ? null : cur.info.packageName;
11596                // Dont allow ephemeral apps to define new permission groups.
11597                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11598                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11599                            + pg.info.packageName
11600                            + " ignored: instant apps cannot define new permission groups.");
11601                    continue;
11602                }
11603                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11604                if (cur == null || isPackageUpdate) {
11605                    mPermissionGroups.put(pg.info.name, pg);
11606                    if (chatty) {
11607                        if (r == null) {
11608                            r = new StringBuilder(256);
11609                        } else {
11610                            r.append(' ');
11611                        }
11612                        if (isPackageUpdate) {
11613                            r.append("UPD:");
11614                        }
11615                        r.append(pg.info.name);
11616                    }
11617                } else {
11618                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11619                            + pg.info.packageName + " ignored: original from "
11620                            + cur.info.packageName);
11621                    if (chatty) {
11622                        if (r == null) {
11623                            r = new StringBuilder(256);
11624                        } else {
11625                            r.append(' ');
11626                        }
11627                        r.append("DUP:");
11628                        r.append(pg.info.name);
11629                    }
11630                }
11631            }
11632            if (r != null) {
11633                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11634            }
11635
11636            N = pkg.permissions.size();
11637            r = null;
11638            for (i=0; i<N; i++) {
11639                PackageParser.Permission p = pkg.permissions.get(i);
11640
11641                // Dont allow ephemeral apps to define new permissions.
11642                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11643                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11644                            + p.info.packageName
11645                            + " ignored: instant apps cannot define new permissions.");
11646                    continue;
11647                }
11648
11649                // Assume by default that we did not install this permission into the system.
11650                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11651
11652                // Now that permission groups have a special meaning, we ignore permission
11653                // groups for legacy apps to prevent unexpected behavior. In particular,
11654                // permissions for one app being granted to someone just because they happen
11655                // to be in a group defined by another app (before this had no implications).
11656                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11657                    p.group = mPermissionGroups.get(p.info.group);
11658                    // Warn for a permission in an unknown group.
11659                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11660                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11661                                + p.info.packageName + " in an unknown group " + p.info.group);
11662                    }
11663                }
11664
11665                ArrayMap<String, BasePermission> permissionMap =
11666                        p.tree ? mSettings.mPermissionTrees
11667                                : mSettings.mPermissions;
11668                BasePermission bp = permissionMap.get(p.info.name);
11669
11670                // Allow system apps to redefine non-system permissions
11671                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11672                    final boolean currentOwnerIsSystem = (bp.perm != null
11673                            && isSystemApp(bp.perm.owner));
11674                    if (isSystemApp(p.owner)) {
11675                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11676                            // It's a built-in permission and no owner, take ownership now
11677                            bp.packageSetting = pkgSetting;
11678                            bp.perm = p;
11679                            bp.uid = pkg.applicationInfo.uid;
11680                            bp.sourcePackage = p.info.packageName;
11681                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11682                        } else if (!currentOwnerIsSystem) {
11683                            String msg = "New decl " + p.owner + " of permission  "
11684                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11685                            reportSettingsProblem(Log.WARN, msg);
11686                            bp = null;
11687                        }
11688                    }
11689                }
11690
11691                if (bp == null) {
11692                    bp = new BasePermission(p.info.name, p.info.packageName,
11693                            BasePermission.TYPE_NORMAL);
11694                    permissionMap.put(p.info.name, bp);
11695                }
11696
11697                if (bp.perm == null) {
11698                    if (bp.sourcePackage == null
11699                            || bp.sourcePackage.equals(p.info.packageName)) {
11700                        BasePermission tree = findPermissionTreeLP(p.info.name);
11701                        if (tree == null
11702                                || tree.sourcePackage.equals(p.info.packageName)) {
11703                            bp.packageSetting = pkgSetting;
11704                            bp.perm = p;
11705                            bp.uid = pkg.applicationInfo.uid;
11706                            bp.sourcePackage = p.info.packageName;
11707                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11708                            if (chatty) {
11709                                if (r == null) {
11710                                    r = new StringBuilder(256);
11711                                } else {
11712                                    r.append(' ');
11713                                }
11714                                r.append(p.info.name);
11715                            }
11716                        } else {
11717                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11718                                    + p.info.packageName + " ignored: base tree "
11719                                    + tree.name + " is from package "
11720                                    + tree.sourcePackage);
11721                        }
11722                    } else {
11723                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11724                                + p.info.packageName + " ignored: original from "
11725                                + bp.sourcePackage);
11726                    }
11727                } else if (chatty) {
11728                    if (r == null) {
11729                        r = new StringBuilder(256);
11730                    } else {
11731                        r.append(' ');
11732                    }
11733                    r.append("DUP:");
11734                    r.append(p.info.name);
11735                }
11736                if (bp.perm == p) {
11737                    bp.protectionLevel = p.info.protectionLevel;
11738                }
11739            }
11740
11741            if (r != null) {
11742                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11743            }
11744
11745            N = pkg.instrumentation.size();
11746            r = null;
11747            for (i=0; i<N; i++) {
11748                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11749                a.info.packageName = pkg.applicationInfo.packageName;
11750                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11751                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11752                a.info.splitNames = pkg.splitNames;
11753                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11754                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11755                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11756                a.info.dataDir = pkg.applicationInfo.dataDir;
11757                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11758                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11759                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11760                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11761                mInstrumentation.put(a.getComponentName(), a);
11762                if (chatty) {
11763                    if (r == null) {
11764                        r = new StringBuilder(256);
11765                    } else {
11766                        r.append(' ');
11767                    }
11768                    r.append(a.info.name);
11769                }
11770            }
11771            if (r != null) {
11772                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11773            }
11774
11775            if (pkg.protectedBroadcasts != null) {
11776                N = pkg.protectedBroadcasts.size();
11777                synchronized (mProtectedBroadcasts) {
11778                    for (i = 0; i < N; i++) {
11779                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11780                    }
11781                }
11782            }
11783        }
11784
11785        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11786    }
11787
11788    /**
11789     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11790     * is derived purely on the basis of the contents of {@code scanFile} and
11791     * {@code cpuAbiOverride}.
11792     *
11793     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11794     */
11795    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11796                                 String cpuAbiOverride, boolean extractLibs,
11797                                 File appLib32InstallDir)
11798            throws PackageManagerException {
11799        // Give ourselves some initial paths; we'll come back for another
11800        // pass once we've determined ABI below.
11801        setNativeLibraryPaths(pkg, appLib32InstallDir);
11802
11803        // We would never need to extract libs for forward-locked and external packages,
11804        // since the container service will do it for us. We shouldn't attempt to
11805        // extract libs from system app when it was not updated.
11806        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11807                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11808            extractLibs = false;
11809        }
11810
11811        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11812        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11813
11814        NativeLibraryHelper.Handle handle = null;
11815        try {
11816            handle = NativeLibraryHelper.Handle.create(pkg);
11817            // TODO(multiArch): This can be null for apps that didn't go through the
11818            // usual installation process. We can calculate it again, like we
11819            // do during install time.
11820            //
11821            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11822            // unnecessary.
11823            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11824
11825            // Null out the abis so that they can be recalculated.
11826            pkg.applicationInfo.primaryCpuAbi = null;
11827            pkg.applicationInfo.secondaryCpuAbi = null;
11828            if (isMultiArch(pkg.applicationInfo)) {
11829                // Warn if we've set an abiOverride for multi-lib packages..
11830                // By definition, we need to copy both 32 and 64 bit libraries for
11831                // such packages.
11832                if (pkg.cpuAbiOverride != null
11833                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11834                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11835                }
11836
11837                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11838                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11839                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11840                    if (extractLibs) {
11841                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11842                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11843                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11844                                useIsaSpecificSubdirs);
11845                    } else {
11846                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11847                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11848                    }
11849                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11850                }
11851
11852                // Shared library native code should be in the APK zip aligned
11853                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11854                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11855                            "Shared library native lib extraction not supported");
11856                }
11857
11858                maybeThrowExceptionForMultiArchCopy(
11859                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11860
11861                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11862                    if (extractLibs) {
11863                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11864                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11865                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11866                                useIsaSpecificSubdirs);
11867                    } else {
11868                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11869                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11870                    }
11871                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11872                }
11873
11874                maybeThrowExceptionForMultiArchCopy(
11875                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11876
11877                if (abi64 >= 0) {
11878                    // Shared library native libs should be in the APK zip aligned
11879                    if (extractLibs && pkg.isLibrary()) {
11880                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11881                                "Shared library native lib extraction not supported");
11882                    }
11883                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11884                }
11885
11886                if (abi32 >= 0) {
11887                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11888                    if (abi64 >= 0) {
11889                        if (pkg.use32bitAbi) {
11890                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11891                            pkg.applicationInfo.primaryCpuAbi = abi;
11892                        } else {
11893                            pkg.applicationInfo.secondaryCpuAbi = abi;
11894                        }
11895                    } else {
11896                        pkg.applicationInfo.primaryCpuAbi = abi;
11897                    }
11898                }
11899            } else {
11900                String[] abiList = (cpuAbiOverride != null) ?
11901                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11902
11903                // Enable gross and lame hacks for apps that are built with old
11904                // SDK tools. We must scan their APKs for renderscript bitcode and
11905                // not launch them if it's present. Don't bother checking on devices
11906                // that don't have 64 bit support.
11907                boolean needsRenderScriptOverride = false;
11908                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11909                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11910                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11911                    needsRenderScriptOverride = true;
11912                }
11913
11914                final int copyRet;
11915                if (extractLibs) {
11916                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11917                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11918                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11919                } else {
11920                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11921                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11922                }
11923                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11924
11925                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11926                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11927                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11928                }
11929
11930                if (copyRet >= 0) {
11931                    // Shared libraries that have native libs must be multi-architecture
11932                    if (pkg.isLibrary()) {
11933                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11934                                "Shared library with native libs must be multiarch");
11935                    }
11936                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11937                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11938                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11939                } else if (needsRenderScriptOverride) {
11940                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11941                }
11942            }
11943        } catch (IOException ioe) {
11944            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11945        } finally {
11946            IoUtils.closeQuietly(handle);
11947        }
11948
11949        // Now that we've calculated the ABIs and determined if it's an internal app,
11950        // we will go ahead and populate the nativeLibraryPath.
11951        setNativeLibraryPaths(pkg, appLib32InstallDir);
11952    }
11953
11954    /**
11955     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11956     * i.e, so that all packages can be run inside a single process if required.
11957     *
11958     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11959     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11960     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11961     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11962     * updating a package that belongs to a shared user.
11963     *
11964     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11965     * adds unnecessary complexity.
11966     */
11967    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11968            PackageParser.Package scannedPackage) {
11969        String requiredInstructionSet = null;
11970        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11971            requiredInstructionSet = VMRuntime.getInstructionSet(
11972                     scannedPackage.applicationInfo.primaryCpuAbi);
11973        }
11974
11975        PackageSetting requirer = null;
11976        for (PackageSetting ps : packagesForUser) {
11977            // If packagesForUser contains scannedPackage, we skip it. This will happen
11978            // when scannedPackage is an update of an existing package. Without this check,
11979            // we will never be able to change the ABI of any package belonging to a shared
11980            // user, even if it's compatible with other packages.
11981            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11982                if (ps.primaryCpuAbiString == null) {
11983                    continue;
11984                }
11985
11986                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11987                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11988                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11989                    // this but there's not much we can do.
11990                    String errorMessage = "Instruction set mismatch, "
11991                            + ((requirer == null) ? "[caller]" : requirer)
11992                            + " requires " + requiredInstructionSet + " whereas " + ps
11993                            + " requires " + instructionSet;
11994                    Slog.w(TAG, errorMessage);
11995                }
11996
11997                if (requiredInstructionSet == null) {
11998                    requiredInstructionSet = instructionSet;
11999                    requirer = ps;
12000                }
12001            }
12002        }
12003
12004        if (requiredInstructionSet != null) {
12005            String adjustedAbi;
12006            if (requirer != null) {
12007                // requirer != null implies that either scannedPackage was null or that scannedPackage
12008                // did not require an ABI, in which case we have to adjust scannedPackage to match
12009                // the ABI of the set (which is the same as requirer's ABI)
12010                adjustedAbi = requirer.primaryCpuAbiString;
12011                if (scannedPackage != null) {
12012                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12013                }
12014            } else {
12015                // requirer == null implies that we're updating all ABIs in the set to
12016                // match scannedPackage.
12017                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12018            }
12019
12020            for (PackageSetting ps : packagesForUser) {
12021                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12022                    if (ps.primaryCpuAbiString != null) {
12023                        continue;
12024                    }
12025
12026                    ps.primaryCpuAbiString = adjustedAbi;
12027                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12028                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12029                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12030                        if (DEBUG_ABI_SELECTION) {
12031                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12032                                    + " (requirer="
12033                                    + (requirer != null ? requirer.pkg : "null")
12034                                    + ", scannedPackage="
12035                                    + (scannedPackage != null ? scannedPackage : "null")
12036                                    + ")");
12037                        }
12038                        try {
12039                            mInstaller.rmdex(ps.codePathString,
12040                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12041                        } catch (InstallerException ignored) {
12042                        }
12043                    }
12044                }
12045            }
12046        }
12047    }
12048
12049    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12050        synchronized (mPackages) {
12051            mResolverReplaced = true;
12052            // Set up information for custom user intent resolution activity.
12053            mResolveActivity.applicationInfo = pkg.applicationInfo;
12054            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12055            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12056            mResolveActivity.processName = pkg.applicationInfo.packageName;
12057            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12058            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12059                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12060            mResolveActivity.theme = 0;
12061            mResolveActivity.exported = true;
12062            mResolveActivity.enabled = true;
12063            mResolveInfo.activityInfo = mResolveActivity;
12064            mResolveInfo.priority = 0;
12065            mResolveInfo.preferredOrder = 0;
12066            mResolveInfo.match = 0;
12067            mResolveComponentName = mCustomResolverComponentName;
12068            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12069                    mResolveComponentName);
12070        }
12071    }
12072
12073    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12074        if (installerActivity == null) {
12075            if (DEBUG_EPHEMERAL) {
12076                Slog.d(TAG, "Clear ephemeral installer activity");
12077            }
12078            mInstantAppInstallerActivity = null;
12079            return;
12080        }
12081
12082        if (DEBUG_EPHEMERAL) {
12083            Slog.d(TAG, "Set ephemeral installer activity: "
12084                    + installerActivity.getComponentName());
12085        }
12086        // Set up information for ephemeral installer activity
12087        mInstantAppInstallerActivity = installerActivity;
12088        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12089                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12090        mInstantAppInstallerActivity.exported = true;
12091        mInstantAppInstallerActivity.enabled = true;
12092        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12093        mInstantAppInstallerInfo.priority = 0;
12094        mInstantAppInstallerInfo.preferredOrder = 1;
12095        mInstantAppInstallerInfo.isDefault = true;
12096        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12097                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12098    }
12099
12100    private static String calculateBundledApkRoot(final String codePathString) {
12101        final File codePath = new File(codePathString);
12102        final File codeRoot;
12103        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12104            codeRoot = Environment.getRootDirectory();
12105        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12106            codeRoot = Environment.getOemDirectory();
12107        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12108            codeRoot = Environment.getVendorDirectory();
12109        } else {
12110            // Unrecognized code path; take its top real segment as the apk root:
12111            // e.g. /something/app/blah.apk => /something
12112            try {
12113                File f = codePath.getCanonicalFile();
12114                File parent = f.getParentFile();    // non-null because codePath is a file
12115                File tmp;
12116                while ((tmp = parent.getParentFile()) != null) {
12117                    f = parent;
12118                    parent = tmp;
12119                }
12120                codeRoot = f;
12121                Slog.w(TAG, "Unrecognized code path "
12122                        + codePath + " - using " + codeRoot);
12123            } catch (IOException e) {
12124                // Can't canonicalize the code path -- shenanigans?
12125                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12126                return Environment.getRootDirectory().getPath();
12127            }
12128        }
12129        return codeRoot.getPath();
12130    }
12131
12132    /**
12133     * Derive and set the location of native libraries for the given package,
12134     * which varies depending on where and how the package was installed.
12135     */
12136    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12137        final ApplicationInfo info = pkg.applicationInfo;
12138        final String codePath = pkg.codePath;
12139        final File codeFile = new File(codePath);
12140        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12141        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12142
12143        info.nativeLibraryRootDir = null;
12144        info.nativeLibraryRootRequiresIsa = false;
12145        info.nativeLibraryDir = null;
12146        info.secondaryNativeLibraryDir = null;
12147
12148        if (isApkFile(codeFile)) {
12149            // Monolithic install
12150            if (bundledApp) {
12151                // If "/system/lib64/apkname" exists, assume that is the per-package
12152                // native library directory to use; otherwise use "/system/lib/apkname".
12153                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12154                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12155                        getPrimaryInstructionSet(info));
12156
12157                // This is a bundled system app so choose the path based on the ABI.
12158                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12159                // is just the default path.
12160                final String apkName = deriveCodePathName(codePath);
12161                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12162                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12163                        apkName).getAbsolutePath();
12164
12165                if (info.secondaryCpuAbi != null) {
12166                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12167                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12168                            secondaryLibDir, apkName).getAbsolutePath();
12169                }
12170            } else if (asecApp) {
12171                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12172                        .getAbsolutePath();
12173            } else {
12174                final String apkName = deriveCodePathName(codePath);
12175                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12176                        .getAbsolutePath();
12177            }
12178
12179            info.nativeLibraryRootRequiresIsa = false;
12180            info.nativeLibraryDir = info.nativeLibraryRootDir;
12181        } else {
12182            // Cluster install
12183            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12184            info.nativeLibraryRootRequiresIsa = true;
12185
12186            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12187                    getPrimaryInstructionSet(info)).getAbsolutePath();
12188
12189            if (info.secondaryCpuAbi != null) {
12190                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12191                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12192            }
12193        }
12194    }
12195
12196    /**
12197     * Calculate the abis and roots for a bundled app. These can uniquely
12198     * be determined from the contents of the system partition, i.e whether
12199     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12200     * of this information, and instead assume that the system was built
12201     * sensibly.
12202     */
12203    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12204                                           PackageSetting pkgSetting) {
12205        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12206
12207        // If "/system/lib64/apkname" exists, assume that is the per-package
12208        // native library directory to use; otherwise use "/system/lib/apkname".
12209        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12210        setBundledAppAbi(pkg, apkRoot, apkName);
12211        // pkgSetting might be null during rescan following uninstall of updates
12212        // to a bundled app, so accommodate that possibility.  The settings in
12213        // that case will be established later from the parsed package.
12214        //
12215        // If the settings aren't null, sync them up with what we've just derived.
12216        // note that apkRoot isn't stored in the package settings.
12217        if (pkgSetting != null) {
12218            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12219            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12220        }
12221    }
12222
12223    /**
12224     * Deduces the ABI of a bundled app and sets the relevant fields on the
12225     * parsed pkg object.
12226     *
12227     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12228     *        under which system libraries are installed.
12229     * @param apkName the name of the installed package.
12230     */
12231    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12232        final File codeFile = new File(pkg.codePath);
12233
12234        final boolean has64BitLibs;
12235        final boolean has32BitLibs;
12236        if (isApkFile(codeFile)) {
12237            // Monolithic install
12238            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12239            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12240        } else {
12241            // Cluster install
12242            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12243            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12244                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12245                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12246                has64BitLibs = (new File(rootDir, isa)).exists();
12247            } else {
12248                has64BitLibs = false;
12249            }
12250            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12251                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12252                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12253                has32BitLibs = (new File(rootDir, isa)).exists();
12254            } else {
12255                has32BitLibs = false;
12256            }
12257        }
12258
12259        if (has64BitLibs && !has32BitLibs) {
12260            // The package has 64 bit libs, but not 32 bit libs. Its primary
12261            // ABI should be 64 bit. We can safely assume here that the bundled
12262            // native libraries correspond to the most preferred ABI in the list.
12263
12264            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12265            pkg.applicationInfo.secondaryCpuAbi = null;
12266        } else if (has32BitLibs && !has64BitLibs) {
12267            // The package has 32 bit libs but not 64 bit libs. Its primary
12268            // ABI should be 32 bit.
12269
12270            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12271            pkg.applicationInfo.secondaryCpuAbi = null;
12272        } else if (has32BitLibs && has64BitLibs) {
12273            // The application has both 64 and 32 bit bundled libraries. We check
12274            // here that the app declares multiArch support, and warn if it doesn't.
12275            //
12276            // We will be lenient here and record both ABIs. The primary will be the
12277            // ABI that's higher on the list, i.e, a device that's configured to prefer
12278            // 64 bit apps will see a 64 bit primary ABI,
12279
12280            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12281                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12282            }
12283
12284            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12285                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12286                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12287            } else {
12288                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12289                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12290            }
12291        } else {
12292            pkg.applicationInfo.primaryCpuAbi = null;
12293            pkg.applicationInfo.secondaryCpuAbi = null;
12294        }
12295    }
12296
12297    private void killApplication(String pkgName, int appId, String reason) {
12298        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12299    }
12300
12301    private void killApplication(String pkgName, int appId, int userId, String reason) {
12302        // Request the ActivityManager to kill the process(only for existing packages)
12303        // so that we do not end up in a confused state while the user is still using the older
12304        // version of the application while the new one gets installed.
12305        final long token = Binder.clearCallingIdentity();
12306        try {
12307            IActivityManager am = ActivityManager.getService();
12308            if (am != null) {
12309                try {
12310                    am.killApplication(pkgName, appId, userId, reason);
12311                } catch (RemoteException e) {
12312                }
12313            }
12314        } finally {
12315            Binder.restoreCallingIdentity(token);
12316        }
12317    }
12318
12319    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12320        // Remove the parent package setting
12321        PackageSetting ps = (PackageSetting) pkg.mExtras;
12322        if (ps != null) {
12323            removePackageLI(ps, chatty);
12324        }
12325        // Remove the child package setting
12326        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12327        for (int i = 0; i < childCount; i++) {
12328            PackageParser.Package childPkg = pkg.childPackages.get(i);
12329            ps = (PackageSetting) childPkg.mExtras;
12330            if (ps != null) {
12331                removePackageLI(ps, chatty);
12332            }
12333        }
12334    }
12335
12336    void removePackageLI(PackageSetting ps, boolean chatty) {
12337        if (DEBUG_INSTALL) {
12338            if (chatty)
12339                Log.d(TAG, "Removing package " + ps.name);
12340        }
12341
12342        // writer
12343        synchronized (mPackages) {
12344            mPackages.remove(ps.name);
12345            final PackageParser.Package pkg = ps.pkg;
12346            if (pkg != null) {
12347                cleanPackageDataStructuresLILPw(pkg, chatty);
12348            }
12349        }
12350    }
12351
12352    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12353        if (DEBUG_INSTALL) {
12354            if (chatty)
12355                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12356        }
12357
12358        // writer
12359        synchronized (mPackages) {
12360            // Remove the parent package
12361            mPackages.remove(pkg.applicationInfo.packageName);
12362            cleanPackageDataStructuresLILPw(pkg, chatty);
12363
12364            // Remove the child packages
12365            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12366            for (int i = 0; i < childCount; i++) {
12367                PackageParser.Package childPkg = pkg.childPackages.get(i);
12368                mPackages.remove(childPkg.applicationInfo.packageName);
12369                cleanPackageDataStructuresLILPw(childPkg, chatty);
12370            }
12371        }
12372    }
12373
12374    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12375        int N = pkg.providers.size();
12376        StringBuilder r = null;
12377        int i;
12378        for (i=0; i<N; i++) {
12379            PackageParser.Provider p = pkg.providers.get(i);
12380            mProviders.removeProvider(p);
12381            if (p.info.authority == null) {
12382
12383                /* There was another ContentProvider with this authority when
12384                 * this app was installed so this authority is null,
12385                 * Ignore it as we don't have to unregister the provider.
12386                 */
12387                continue;
12388            }
12389            String names[] = p.info.authority.split(";");
12390            for (int j = 0; j < names.length; j++) {
12391                if (mProvidersByAuthority.get(names[j]) == p) {
12392                    mProvidersByAuthority.remove(names[j]);
12393                    if (DEBUG_REMOVE) {
12394                        if (chatty)
12395                            Log.d(TAG, "Unregistered content provider: " + names[j]
12396                                    + ", className = " + p.info.name + ", isSyncable = "
12397                                    + p.info.isSyncable);
12398                    }
12399                }
12400            }
12401            if (DEBUG_REMOVE && chatty) {
12402                if (r == null) {
12403                    r = new StringBuilder(256);
12404                } else {
12405                    r.append(' ');
12406                }
12407                r.append(p.info.name);
12408            }
12409        }
12410        if (r != null) {
12411            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12412        }
12413
12414        N = pkg.services.size();
12415        r = null;
12416        for (i=0; i<N; i++) {
12417            PackageParser.Service s = pkg.services.get(i);
12418            mServices.removeService(s);
12419            if (chatty) {
12420                if (r == null) {
12421                    r = new StringBuilder(256);
12422                } else {
12423                    r.append(' ');
12424                }
12425                r.append(s.info.name);
12426            }
12427        }
12428        if (r != null) {
12429            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12430        }
12431
12432        N = pkg.receivers.size();
12433        r = null;
12434        for (i=0; i<N; i++) {
12435            PackageParser.Activity a = pkg.receivers.get(i);
12436            mReceivers.removeActivity(a, "receiver");
12437            if (DEBUG_REMOVE && chatty) {
12438                if (r == null) {
12439                    r = new StringBuilder(256);
12440                } else {
12441                    r.append(' ');
12442                }
12443                r.append(a.info.name);
12444            }
12445        }
12446        if (r != null) {
12447            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12448        }
12449
12450        N = pkg.activities.size();
12451        r = null;
12452        for (i=0; i<N; i++) {
12453            PackageParser.Activity a = pkg.activities.get(i);
12454            mActivities.removeActivity(a, "activity");
12455            if (DEBUG_REMOVE && chatty) {
12456                if (r == null) {
12457                    r = new StringBuilder(256);
12458                } else {
12459                    r.append(' ');
12460                }
12461                r.append(a.info.name);
12462            }
12463        }
12464        if (r != null) {
12465            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12466        }
12467
12468        N = pkg.permissions.size();
12469        r = null;
12470        for (i=0; i<N; i++) {
12471            PackageParser.Permission p = pkg.permissions.get(i);
12472            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12473            if (bp == null) {
12474                bp = mSettings.mPermissionTrees.get(p.info.name);
12475            }
12476            if (bp != null && bp.perm == p) {
12477                bp.perm = null;
12478                if (DEBUG_REMOVE && chatty) {
12479                    if (r == null) {
12480                        r = new StringBuilder(256);
12481                    } else {
12482                        r.append(' ');
12483                    }
12484                    r.append(p.info.name);
12485                }
12486            }
12487            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12488                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12489                if (appOpPkgs != null) {
12490                    appOpPkgs.remove(pkg.packageName);
12491                }
12492            }
12493        }
12494        if (r != null) {
12495            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12496        }
12497
12498        N = pkg.requestedPermissions.size();
12499        r = null;
12500        for (i=0; i<N; i++) {
12501            String perm = pkg.requestedPermissions.get(i);
12502            BasePermission bp = mSettings.mPermissions.get(perm);
12503            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12504                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12505                if (appOpPkgs != null) {
12506                    appOpPkgs.remove(pkg.packageName);
12507                    if (appOpPkgs.isEmpty()) {
12508                        mAppOpPermissionPackages.remove(perm);
12509                    }
12510                }
12511            }
12512        }
12513        if (r != null) {
12514            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12515        }
12516
12517        N = pkg.instrumentation.size();
12518        r = null;
12519        for (i=0; i<N; i++) {
12520            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12521            mInstrumentation.remove(a.getComponentName());
12522            if (DEBUG_REMOVE && chatty) {
12523                if (r == null) {
12524                    r = new StringBuilder(256);
12525                } else {
12526                    r.append(' ');
12527                }
12528                r.append(a.info.name);
12529            }
12530        }
12531        if (r != null) {
12532            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12533        }
12534
12535        r = null;
12536        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12537            // Only system apps can hold shared libraries.
12538            if (pkg.libraryNames != null) {
12539                for (i = 0; i < pkg.libraryNames.size(); i++) {
12540                    String name = pkg.libraryNames.get(i);
12541                    if (removeSharedLibraryLPw(name, 0)) {
12542                        if (DEBUG_REMOVE && chatty) {
12543                            if (r == null) {
12544                                r = new StringBuilder(256);
12545                            } else {
12546                                r.append(' ');
12547                            }
12548                            r.append(name);
12549                        }
12550                    }
12551                }
12552            }
12553        }
12554
12555        r = null;
12556
12557        // Any package can hold static shared libraries.
12558        if (pkg.staticSharedLibName != null) {
12559            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12560                if (DEBUG_REMOVE && chatty) {
12561                    if (r == null) {
12562                        r = new StringBuilder(256);
12563                    } else {
12564                        r.append(' ');
12565                    }
12566                    r.append(pkg.staticSharedLibName);
12567                }
12568            }
12569        }
12570
12571        if (r != null) {
12572            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12573        }
12574    }
12575
12576    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12577        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12578            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12579                return true;
12580            }
12581        }
12582        return false;
12583    }
12584
12585    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12586    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12587    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12588
12589    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12590        // Update the parent permissions
12591        updatePermissionsLPw(pkg.packageName, pkg, flags);
12592        // Update the child permissions
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            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12597        }
12598    }
12599
12600    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12601            int flags) {
12602        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12603        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12604    }
12605
12606    private void updatePermissionsLPw(String changingPkg,
12607            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12608        // Make sure there are no dangling permission trees.
12609        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12610        while (it.hasNext()) {
12611            final BasePermission bp = it.next();
12612            if (bp.packageSetting == null) {
12613                // We may not yet have parsed the package, so just see if
12614                // we still know about its settings.
12615                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12616            }
12617            if (bp.packageSetting == null) {
12618                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12619                        + " from package " + bp.sourcePackage);
12620                it.remove();
12621            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12622                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12623                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12624                            + " from package " + bp.sourcePackage);
12625                    flags |= UPDATE_PERMISSIONS_ALL;
12626                    it.remove();
12627                }
12628            }
12629        }
12630
12631        // Make sure all dynamic permissions have been assigned to a package,
12632        // and make sure there are no dangling permissions.
12633        it = mSettings.mPermissions.values().iterator();
12634        while (it.hasNext()) {
12635            final BasePermission bp = it.next();
12636            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12637                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12638                        + bp.name + " pkg=" + bp.sourcePackage
12639                        + " info=" + bp.pendingInfo);
12640                if (bp.packageSetting == null && bp.pendingInfo != null) {
12641                    final BasePermission tree = findPermissionTreeLP(bp.name);
12642                    if (tree != null && tree.perm != null) {
12643                        bp.packageSetting = tree.packageSetting;
12644                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12645                                new PermissionInfo(bp.pendingInfo));
12646                        bp.perm.info.packageName = tree.perm.info.packageName;
12647                        bp.perm.info.name = bp.name;
12648                        bp.uid = tree.uid;
12649                    }
12650                }
12651            }
12652            if (bp.packageSetting == null) {
12653                // We may not yet have parsed the package, so just see if
12654                // we still know about its settings.
12655                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12656            }
12657            if (bp.packageSetting == null) {
12658                Slog.w(TAG, "Removing dangling permission: " + bp.name
12659                        + " from package " + bp.sourcePackage);
12660                it.remove();
12661            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12662                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12663                    Slog.i(TAG, "Removing old permission: " + bp.name
12664                            + " from package " + bp.sourcePackage);
12665                    flags |= UPDATE_PERMISSIONS_ALL;
12666                    it.remove();
12667                }
12668            }
12669        }
12670
12671        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12672        // Now update the permissions for all packages, in particular
12673        // replace the granted permissions of the system packages.
12674        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12675            for (PackageParser.Package pkg : mPackages.values()) {
12676                if (pkg != pkgInfo) {
12677                    // Only replace for packages on requested volume
12678                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12679                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12680                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12681                    grantPermissionsLPw(pkg, replace, changingPkg);
12682                }
12683            }
12684        }
12685
12686        if (pkgInfo != null) {
12687            // Only replace for packages on requested volume
12688            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12689            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12690                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12691            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12692        }
12693        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12694    }
12695
12696    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12697            String packageOfInterest) {
12698        // IMPORTANT: There are two types of permissions: install and runtime.
12699        // Install time permissions are granted when the app is installed to
12700        // all device users and users added in the future. Runtime permissions
12701        // are granted at runtime explicitly to specific users. Normal and signature
12702        // protected permissions are install time permissions. Dangerous permissions
12703        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12704        // otherwise they are runtime permissions. This function does not manage
12705        // runtime permissions except for the case an app targeting Lollipop MR1
12706        // being upgraded to target a newer SDK, in which case dangerous permissions
12707        // are transformed from install time to runtime ones.
12708
12709        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12710        if (ps == null) {
12711            return;
12712        }
12713
12714        PermissionsState permissionsState = ps.getPermissionsState();
12715        PermissionsState origPermissions = permissionsState;
12716
12717        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12718
12719        boolean runtimePermissionsRevoked = false;
12720        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12721
12722        boolean changedInstallPermission = false;
12723
12724        if (replace) {
12725            ps.installPermissionsFixed = false;
12726            if (!ps.isSharedUser()) {
12727                origPermissions = new PermissionsState(permissionsState);
12728                permissionsState.reset();
12729            } else {
12730                // We need to know only about runtime permission changes since the
12731                // calling code always writes the install permissions state but
12732                // the runtime ones are written only if changed. The only cases of
12733                // changed runtime permissions here are promotion of an install to
12734                // runtime and revocation of a runtime from a shared user.
12735                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12736                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12737                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12738                    runtimePermissionsRevoked = true;
12739                }
12740            }
12741        }
12742
12743        permissionsState.setGlobalGids(mGlobalGids);
12744
12745        final int N = pkg.requestedPermissions.size();
12746        for (int i=0; i<N; i++) {
12747            final String name = pkg.requestedPermissions.get(i);
12748            final BasePermission bp = mSettings.mPermissions.get(name);
12749            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12750                    >= Build.VERSION_CODES.M;
12751
12752            if (DEBUG_INSTALL) {
12753                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12754            }
12755
12756            if (bp == null || bp.packageSetting == null) {
12757                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12758                    if (DEBUG_PERMISSIONS) {
12759                        Slog.i(TAG, "Unknown permission " + name
12760                                + " in package " + pkg.packageName);
12761                    }
12762                }
12763                continue;
12764            }
12765
12766
12767            // Limit ephemeral apps to ephemeral allowed permissions.
12768            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12769                if (DEBUG_PERMISSIONS) {
12770                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12771                            + pkg.packageName);
12772                }
12773                continue;
12774            }
12775
12776            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12777                if (DEBUG_PERMISSIONS) {
12778                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12779                            + pkg.packageName);
12780                }
12781                continue;
12782            }
12783
12784            final String perm = bp.name;
12785            boolean allowedSig = false;
12786            int grant = GRANT_DENIED;
12787
12788            // Keep track of app op permissions.
12789            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12790                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12791                if (pkgs == null) {
12792                    pkgs = new ArraySet<>();
12793                    mAppOpPermissionPackages.put(bp.name, pkgs);
12794                }
12795                pkgs.add(pkg.packageName);
12796            }
12797
12798            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12799            switch (level) {
12800                case PermissionInfo.PROTECTION_NORMAL: {
12801                    // For all apps normal permissions are install time ones.
12802                    grant = GRANT_INSTALL;
12803                } break;
12804
12805                case PermissionInfo.PROTECTION_DANGEROUS: {
12806                    // If a permission review is required for legacy apps we represent
12807                    // their permissions as always granted runtime ones since we need
12808                    // to keep the review required permission flag per user while an
12809                    // install permission's state is shared across all users.
12810                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12811                        // For legacy apps dangerous permissions are install time ones.
12812                        grant = GRANT_INSTALL;
12813                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12814                        // For legacy apps that became modern, install becomes runtime.
12815                        grant = GRANT_UPGRADE;
12816                    } else if (mPromoteSystemApps
12817                            && isSystemApp(ps)
12818                            && mExistingSystemPackages.contains(ps.name)) {
12819                        // For legacy system apps, install becomes runtime.
12820                        // We cannot check hasInstallPermission() for system apps since those
12821                        // permissions were granted implicitly and not persisted pre-M.
12822                        grant = GRANT_UPGRADE;
12823                    } else {
12824                        // For modern apps keep runtime permissions unchanged.
12825                        grant = GRANT_RUNTIME;
12826                    }
12827                } break;
12828
12829                case PermissionInfo.PROTECTION_SIGNATURE: {
12830                    // For all apps signature permissions are install time ones.
12831                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12832                    if (allowedSig) {
12833                        grant = GRANT_INSTALL;
12834                    }
12835                } break;
12836            }
12837
12838            if (DEBUG_PERMISSIONS) {
12839                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12840            }
12841
12842            if (grant != GRANT_DENIED) {
12843                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12844                    // If this is an existing, non-system package, then
12845                    // we can't add any new permissions to it.
12846                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12847                        // Except...  if this is a permission that was added
12848                        // to the platform (note: need to only do this when
12849                        // updating the platform).
12850                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12851                            grant = GRANT_DENIED;
12852                        }
12853                    }
12854                }
12855
12856                switch (grant) {
12857                    case GRANT_INSTALL: {
12858                        // Revoke this as runtime permission to handle the case of
12859                        // a runtime permission being downgraded to an install one.
12860                        // Also in permission review mode we keep dangerous permissions
12861                        // for legacy apps
12862                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12863                            if (origPermissions.getRuntimePermissionState(
12864                                    bp.name, userId) != null) {
12865                                // Revoke the runtime permission and clear the flags.
12866                                origPermissions.revokeRuntimePermission(bp, userId);
12867                                origPermissions.updatePermissionFlags(bp, userId,
12868                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12869                                // If we revoked a permission permission, we have to write.
12870                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12871                                        changedRuntimePermissionUserIds, userId);
12872                            }
12873                        }
12874                        // Grant an install permission.
12875                        if (permissionsState.grantInstallPermission(bp) !=
12876                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12877                            changedInstallPermission = true;
12878                        }
12879                    } break;
12880
12881                    case GRANT_RUNTIME: {
12882                        // Grant previously granted runtime permissions.
12883                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12884                            PermissionState permissionState = origPermissions
12885                                    .getRuntimePermissionState(bp.name, userId);
12886                            int flags = permissionState != null
12887                                    ? permissionState.getFlags() : 0;
12888                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12889                                // Don't propagate the permission in a permission review mode if
12890                                // the former was revoked, i.e. marked to not propagate on upgrade.
12891                                // Note that in a permission review mode install permissions are
12892                                // represented as constantly granted runtime ones since we need to
12893                                // keep a per user state associated with the permission. Also the
12894                                // revoke on upgrade flag is no longer applicable and is reset.
12895                                final boolean revokeOnUpgrade = (flags & PackageManager
12896                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12897                                if (revokeOnUpgrade) {
12898                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12899                                    // Since we changed the flags, we have to write.
12900                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12901                                            changedRuntimePermissionUserIds, userId);
12902                                }
12903                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12904                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12905                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12906                                        // If we cannot put the permission as it was,
12907                                        // we have to write.
12908                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12909                                                changedRuntimePermissionUserIds, userId);
12910                                    }
12911                                }
12912
12913                                // If the app supports runtime permissions no need for a review.
12914                                if (mPermissionReviewRequired
12915                                        && appSupportsRuntimePermissions
12916                                        && (flags & PackageManager
12917                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12918                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12919                                    // Since we changed the flags, we have to write.
12920                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12921                                            changedRuntimePermissionUserIds, userId);
12922                                }
12923                            } else if (mPermissionReviewRequired
12924                                    && !appSupportsRuntimePermissions) {
12925                                // For legacy apps that need a permission review, every new
12926                                // runtime permission is granted but it is pending a review.
12927                                // We also need to review only platform defined runtime
12928                                // permissions as these are the only ones the platform knows
12929                                // how to disable the API to simulate revocation as legacy
12930                                // apps don't expect to run with revoked permissions.
12931                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12932                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12933                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12934                                        // We changed the flags, hence have to write.
12935                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12936                                                changedRuntimePermissionUserIds, userId);
12937                                    }
12938                                }
12939                                if (permissionsState.grantRuntimePermission(bp, userId)
12940                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12941                                    // We changed the permission, hence have to write.
12942                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12943                                            changedRuntimePermissionUserIds, userId);
12944                                }
12945                            }
12946                            // Propagate the permission flags.
12947                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12948                        }
12949                    } break;
12950
12951                    case GRANT_UPGRADE: {
12952                        // Grant runtime permissions for a previously held install permission.
12953                        PermissionState permissionState = origPermissions
12954                                .getInstallPermissionState(bp.name);
12955                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12956
12957                        if (origPermissions.revokeInstallPermission(bp)
12958                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12959                            // We will be transferring the permission flags, so clear them.
12960                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12961                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12962                            changedInstallPermission = true;
12963                        }
12964
12965                        // If the permission is not to be promoted to runtime we ignore it and
12966                        // also its other flags as they are not applicable to install permissions.
12967                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12968                            for (int userId : currentUserIds) {
12969                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12970                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12971                                    // Transfer the permission flags.
12972                                    permissionsState.updatePermissionFlags(bp, userId,
12973                                            flags, flags);
12974                                    // If we granted the permission, we have to write.
12975                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12976                                            changedRuntimePermissionUserIds, userId);
12977                                }
12978                            }
12979                        }
12980                    } break;
12981
12982                    default: {
12983                        if (packageOfInterest == null
12984                                || packageOfInterest.equals(pkg.packageName)) {
12985                            if (DEBUG_PERMISSIONS) {
12986                                Slog.i(TAG, "Not granting permission " + perm
12987                                        + " to package " + pkg.packageName
12988                                        + " because it was previously installed without");
12989                            }
12990                        }
12991                    } break;
12992                }
12993            } else {
12994                if (permissionsState.revokeInstallPermission(bp) !=
12995                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12996                    // Also drop the permission flags.
12997                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12998                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12999                    changedInstallPermission = true;
13000                    Slog.i(TAG, "Un-granting permission " + perm
13001                            + " from package " + pkg.packageName
13002                            + " (protectionLevel=" + bp.protectionLevel
13003                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13004                            + ")");
13005                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13006                    // Don't print warning for app op permissions, since it is fine for them
13007                    // not to be granted, there is a UI for the user to decide.
13008                    if (DEBUG_PERMISSIONS
13009                            && (packageOfInterest == null
13010                                    || packageOfInterest.equals(pkg.packageName))) {
13011                        Slog.i(TAG, "Not granting permission " + perm
13012                                + " to package " + pkg.packageName
13013                                + " (protectionLevel=" + bp.protectionLevel
13014                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13015                                + ")");
13016                    }
13017                }
13018            }
13019        }
13020
13021        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13022                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13023            // This is the first that we have heard about this package, so the
13024            // permissions we have now selected are fixed until explicitly
13025            // changed.
13026            ps.installPermissionsFixed = true;
13027        }
13028
13029        // Persist the runtime permissions state for users with changes. If permissions
13030        // were revoked because no app in the shared user declares them we have to
13031        // write synchronously to avoid losing runtime permissions state.
13032        for (int userId : changedRuntimePermissionUserIds) {
13033            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13034        }
13035    }
13036
13037    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13038        boolean allowed = false;
13039        final int NP = PackageParser.NEW_PERMISSIONS.length;
13040        for (int ip=0; ip<NP; ip++) {
13041            final PackageParser.NewPermissionInfo npi
13042                    = PackageParser.NEW_PERMISSIONS[ip];
13043            if (npi.name.equals(perm)
13044                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13045                allowed = true;
13046                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13047                        + pkg.packageName);
13048                break;
13049            }
13050        }
13051        return allowed;
13052    }
13053
13054    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13055            BasePermission bp, PermissionsState origPermissions) {
13056        boolean privilegedPermission = (bp.protectionLevel
13057                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13058        boolean privappPermissionsDisable =
13059                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13060        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13061        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13062        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13063                && !platformPackage && platformPermission) {
13064            ArraySet<String> wlPermissions = SystemConfig.getInstance()
13065                    .getPrivAppPermissions(pkg.packageName);
13066            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
13067            if (!whitelisted) {
13068                Slog.w(TAG, "Privileged permission " + perm + " for package "
13069                        + pkg.packageName + " - not in privapp-permissions whitelist");
13070                // Only report violations for apps on system image
13071                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13072                    if (mPrivappPermissionsViolations == null) {
13073                        mPrivappPermissionsViolations = new ArraySet<>();
13074                    }
13075                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13076                }
13077                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13078                    return false;
13079                }
13080            }
13081        }
13082        boolean allowed = (compareSignatures(
13083                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13084                        == PackageManager.SIGNATURE_MATCH)
13085                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13086                        == PackageManager.SIGNATURE_MATCH);
13087        if (!allowed && privilegedPermission) {
13088            if (isSystemApp(pkg)) {
13089                // For updated system applications, a system permission
13090                // is granted only if it had been defined by the original application.
13091                if (pkg.isUpdatedSystemApp()) {
13092                    final PackageSetting sysPs = mSettings
13093                            .getDisabledSystemPkgLPr(pkg.packageName);
13094                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13095                        // If the original was granted this permission, we take
13096                        // that grant decision as read and propagate it to the
13097                        // update.
13098                        if (sysPs.isPrivileged()) {
13099                            allowed = true;
13100                        }
13101                    } else {
13102                        // The system apk may have been updated with an older
13103                        // version of the one on the data partition, but which
13104                        // granted a new system permission that it didn't have
13105                        // before.  In this case we do want to allow the app to
13106                        // now get the new permission if the ancestral apk is
13107                        // privileged to get it.
13108                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13109                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13110                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13111                                    allowed = true;
13112                                    break;
13113                                }
13114                            }
13115                        }
13116                        // Also if a privileged parent package on the system image or any of
13117                        // its children requested a privileged permission, the updated child
13118                        // packages can also get the permission.
13119                        if (pkg.parentPackage != null) {
13120                            final PackageSetting disabledSysParentPs = mSettings
13121                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13122                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13123                                    && disabledSysParentPs.isPrivileged()) {
13124                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13125                                    allowed = true;
13126                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13127                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13128                                    for (int i = 0; i < count; i++) {
13129                                        PackageParser.Package disabledSysChildPkg =
13130                                                disabledSysParentPs.pkg.childPackages.get(i);
13131                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13132                                                perm)) {
13133                                            allowed = true;
13134                                            break;
13135                                        }
13136                                    }
13137                                }
13138                            }
13139                        }
13140                    }
13141                } else {
13142                    allowed = isPrivilegedApp(pkg);
13143                }
13144            }
13145        }
13146        if (!allowed) {
13147            if (!allowed && (bp.protectionLevel
13148                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13149                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13150                // If this was a previously normal/dangerous permission that got moved
13151                // to a system permission as part of the runtime permission redesign, then
13152                // we still want to blindly grant it to old apps.
13153                allowed = true;
13154            }
13155            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13156                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13157                // If this permission is to be granted to the system installer and
13158                // this app is an installer, then it gets the permission.
13159                allowed = true;
13160            }
13161            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13162                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13163                // If this permission is to be granted to the system verifier and
13164                // this app is a verifier, then it gets the permission.
13165                allowed = true;
13166            }
13167            if (!allowed && (bp.protectionLevel
13168                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13169                    && isSystemApp(pkg)) {
13170                // Any pre-installed system app is allowed to get this permission.
13171                allowed = true;
13172            }
13173            if (!allowed && (bp.protectionLevel
13174                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13175                // For development permissions, a development permission
13176                // is granted only if it was already granted.
13177                allowed = origPermissions.hasInstallPermission(perm);
13178            }
13179            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13180                    && pkg.packageName.equals(mSetupWizardPackage)) {
13181                // If this permission is to be granted to the system setup wizard and
13182                // this app is a setup wizard, then it gets the permission.
13183                allowed = true;
13184            }
13185        }
13186        return allowed;
13187    }
13188
13189    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13190        final int permCount = pkg.requestedPermissions.size();
13191        for (int j = 0; j < permCount; j++) {
13192            String requestedPermission = pkg.requestedPermissions.get(j);
13193            if (permission.equals(requestedPermission)) {
13194                return true;
13195            }
13196        }
13197        return false;
13198    }
13199
13200    final class ActivityIntentResolver
13201            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13202        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13203                boolean defaultOnly, int userId) {
13204            if (!sUserManager.exists(userId)) return null;
13205            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13206            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13207        }
13208
13209        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13210                int userId) {
13211            if (!sUserManager.exists(userId)) return null;
13212            mFlags = flags;
13213            return super.queryIntent(intent, resolvedType,
13214                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13215                    userId);
13216        }
13217
13218        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13219                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13220            if (!sUserManager.exists(userId)) return null;
13221            if (packageActivities == null) {
13222                return null;
13223            }
13224            mFlags = flags;
13225            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13226            final int N = packageActivities.size();
13227            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13228                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13229
13230            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13231            for (int i = 0; i < N; ++i) {
13232                intentFilters = packageActivities.get(i).intents;
13233                if (intentFilters != null && intentFilters.size() > 0) {
13234                    PackageParser.ActivityIntentInfo[] array =
13235                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13236                    intentFilters.toArray(array);
13237                    listCut.add(array);
13238                }
13239            }
13240            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13241        }
13242
13243        /**
13244         * Finds a privileged activity that matches the specified activity names.
13245         */
13246        private PackageParser.Activity findMatchingActivity(
13247                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13248            for (PackageParser.Activity sysActivity : activityList) {
13249                if (sysActivity.info.name.equals(activityInfo.name)) {
13250                    return sysActivity;
13251                }
13252                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13253                    return sysActivity;
13254                }
13255                if (sysActivity.info.targetActivity != null) {
13256                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13257                        return sysActivity;
13258                    }
13259                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13260                        return sysActivity;
13261                    }
13262                }
13263            }
13264            return null;
13265        }
13266
13267        public class IterGenerator<E> {
13268            public Iterator<E> generate(ActivityIntentInfo info) {
13269                return null;
13270            }
13271        }
13272
13273        public class ActionIterGenerator extends IterGenerator<String> {
13274            @Override
13275            public Iterator<String> generate(ActivityIntentInfo info) {
13276                return info.actionsIterator();
13277            }
13278        }
13279
13280        public class CategoriesIterGenerator extends IterGenerator<String> {
13281            @Override
13282            public Iterator<String> generate(ActivityIntentInfo info) {
13283                return info.categoriesIterator();
13284            }
13285        }
13286
13287        public class SchemesIterGenerator extends IterGenerator<String> {
13288            @Override
13289            public Iterator<String> generate(ActivityIntentInfo info) {
13290                return info.schemesIterator();
13291            }
13292        }
13293
13294        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13295            @Override
13296            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13297                return info.authoritiesIterator();
13298            }
13299        }
13300
13301        /**
13302         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13303         * MODIFIED. Do not pass in a list that should not be changed.
13304         */
13305        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13306                IterGenerator<T> generator, Iterator<T> searchIterator) {
13307            // loop through the set of actions; every one must be found in the intent filter
13308            while (searchIterator.hasNext()) {
13309                // we must have at least one filter in the list to consider a match
13310                if (intentList.size() == 0) {
13311                    break;
13312                }
13313
13314                final T searchAction = searchIterator.next();
13315
13316                // loop through the set of intent filters
13317                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13318                while (intentIter.hasNext()) {
13319                    final ActivityIntentInfo intentInfo = intentIter.next();
13320                    boolean selectionFound = false;
13321
13322                    // loop through the intent filter's selection criteria; at least one
13323                    // of them must match the searched criteria
13324                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13325                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13326                        final T intentSelection = intentSelectionIter.next();
13327                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13328                            selectionFound = true;
13329                            break;
13330                        }
13331                    }
13332
13333                    // the selection criteria wasn't found in this filter's set; this filter
13334                    // is not a potential match
13335                    if (!selectionFound) {
13336                        intentIter.remove();
13337                    }
13338                }
13339            }
13340        }
13341
13342        private boolean isProtectedAction(ActivityIntentInfo filter) {
13343            final Iterator<String> actionsIter = filter.actionsIterator();
13344            while (actionsIter != null && actionsIter.hasNext()) {
13345                final String filterAction = actionsIter.next();
13346                if (PROTECTED_ACTIONS.contains(filterAction)) {
13347                    return true;
13348                }
13349            }
13350            return false;
13351        }
13352
13353        /**
13354         * Adjusts the priority of the given intent filter according to policy.
13355         * <p>
13356         * <ul>
13357         * <li>The priority for non privileged applications is capped to '0'</li>
13358         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13359         * <li>The priority for unbundled updates to privileged applications is capped to the
13360         *      priority defined on the system partition</li>
13361         * </ul>
13362         * <p>
13363         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13364         * allowed to obtain any priority on any action.
13365         */
13366        private void adjustPriority(
13367                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13368            // nothing to do; priority is fine as-is
13369            if (intent.getPriority() <= 0) {
13370                return;
13371            }
13372
13373            final ActivityInfo activityInfo = intent.activity.info;
13374            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13375
13376            final boolean privilegedApp =
13377                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13378            if (!privilegedApp) {
13379                // non-privileged applications can never define a priority >0
13380                if (DEBUG_FILTERS) {
13381                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13382                            + " package: " + applicationInfo.packageName
13383                            + " activity: " + intent.activity.className
13384                            + " origPrio: " + intent.getPriority());
13385                }
13386                intent.setPriority(0);
13387                return;
13388            }
13389
13390            if (systemActivities == null) {
13391                // the system package is not disabled; we're parsing the system partition
13392                if (isProtectedAction(intent)) {
13393                    if (mDeferProtectedFilters) {
13394                        // We can't deal with these just yet. No component should ever obtain a
13395                        // >0 priority for a protected actions, with ONE exception -- the setup
13396                        // wizard. The setup wizard, however, cannot be known until we're able to
13397                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13398                        // until all intent filters have been processed. Chicken, meet egg.
13399                        // Let the filter temporarily have a high priority and rectify the
13400                        // priorities after all system packages have been scanned.
13401                        mProtectedFilters.add(intent);
13402                        if (DEBUG_FILTERS) {
13403                            Slog.i(TAG, "Protected action; save for later;"
13404                                    + " package: " + applicationInfo.packageName
13405                                    + " activity: " + intent.activity.className
13406                                    + " origPrio: " + intent.getPriority());
13407                        }
13408                        return;
13409                    } else {
13410                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13411                            Slog.i(TAG, "No setup wizard;"
13412                                + " All protected intents capped to priority 0");
13413                        }
13414                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13415                            if (DEBUG_FILTERS) {
13416                                Slog.i(TAG, "Found setup wizard;"
13417                                    + " allow priority " + intent.getPriority() + ";"
13418                                    + " package: " + intent.activity.info.packageName
13419                                    + " activity: " + intent.activity.className
13420                                    + " priority: " + intent.getPriority());
13421                            }
13422                            // setup wizard gets whatever it wants
13423                            return;
13424                        }
13425                        if (DEBUG_FILTERS) {
13426                            Slog.i(TAG, "Protected action; cap priority to 0;"
13427                                    + " package: " + intent.activity.info.packageName
13428                                    + " activity: " + intent.activity.className
13429                                    + " origPrio: " + intent.getPriority());
13430                        }
13431                        intent.setPriority(0);
13432                        return;
13433                    }
13434                }
13435                // privileged apps on the system image get whatever priority they request
13436                return;
13437            }
13438
13439            // privileged app unbundled update ... try to find the same activity
13440            final PackageParser.Activity foundActivity =
13441                    findMatchingActivity(systemActivities, activityInfo);
13442            if (foundActivity == null) {
13443                // this is a new activity; it cannot obtain >0 priority
13444                if (DEBUG_FILTERS) {
13445                    Slog.i(TAG, "New activity; cap priority to 0;"
13446                            + " package: " + applicationInfo.packageName
13447                            + " activity: " + intent.activity.className
13448                            + " origPrio: " + intent.getPriority());
13449                }
13450                intent.setPriority(0);
13451                return;
13452            }
13453
13454            // found activity, now check for filter equivalence
13455
13456            // a shallow copy is enough; we modify the list, not its contents
13457            final List<ActivityIntentInfo> intentListCopy =
13458                    new ArrayList<>(foundActivity.intents);
13459            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13460
13461            // find matching action subsets
13462            final Iterator<String> actionsIterator = intent.actionsIterator();
13463            if (actionsIterator != null) {
13464                getIntentListSubset(
13465                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13466                if (intentListCopy.size() == 0) {
13467                    // no more intents to match; we're not equivalent
13468                    if (DEBUG_FILTERS) {
13469                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13470                                + " package: " + applicationInfo.packageName
13471                                + " activity: " + intent.activity.className
13472                                + " origPrio: " + intent.getPriority());
13473                    }
13474                    intent.setPriority(0);
13475                    return;
13476                }
13477            }
13478
13479            // find matching category subsets
13480            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13481            if (categoriesIterator != null) {
13482                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13483                        categoriesIterator);
13484                if (intentListCopy.size() == 0) {
13485                    // no more intents to match; we're not equivalent
13486                    if (DEBUG_FILTERS) {
13487                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13488                                + " package: " + applicationInfo.packageName
13489                                + " activity: " + intent.activity.className
13490                                + " origPrio: " + intent.getPriority());
13491                    }
13492                    intent.setPriority(0);
13493                    return;
13494                }
13495            }
13496
13497            // find matching schemes subsets
13498            final Iterator<String> schemesIterator = intent.schemesIterator();
13499            if (schemesIterator != null) {
13500                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13501                        schemesIterator);
13502                if (intentListCopy.size() == 0) {
13503                    // no more intents to match; we're not equivalent
13504                    if (DEBUG_FILTERS) {
13505                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13506                                + " package: " + applicationInfo.packageName
13507                                + " activity: " + intent.activity.className
13508                                + " origPrio: " + intent.getPriority());
13509                    }
13510                    intent.setPriority(0);
13511                    return;
13512                }
13513            }
13514
13515            // find matching authorities subsets
13516            final Iterator<IntentFilter.AuthorityEntry>
13517                    authoritiesIterator = intent.authoritiesIterator();
13518            if (authoritiesIterator != null) {
13519                getIntentListSubset(intentListCopy,
13520                        new AuthoritiesIterGenerator(),
13521                        authoritiesIterator);
13522                if (intentListCopy.size() == 0) {
13523                    // no more intents to match; we're not equivalent
13524                    if (DEBUG_FILTERS) {
13525                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13526                                + " package: " + applicationInfo.packageName
13527                                + " activity: " + intent.activity.className
13528                                + " origPrio: " + intent.getPriority());
13529                    }
13530                    intent.setPriority(0);
13531                    return;
13532                }
13533            }
13534
13535            // we found matching filter(s); app gets the max priority of all intents
13536            int cappedPriority = 0;
13537            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13538                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13539            }
13540            if (intent.getPriority() > cappedPriority) {
13541                if (DEBUG_FILTERS) {
13542                    Slog.i(TAG, "Found matching filter(s);"
13543                            + " cap priority to " + cappedPriority + ";"
13544                            + " package: " + applicationInfo.packageName
13545                            + " activity: " + intent.activity.className
13546                            + " origPrio: " + intent.getPriority());
13547                }
13548                intent.setPriority(cappedPriority);
13549                return;
13550            }
13551            // all this for nothing; the requested priority was <= what was on the system
13552        }
13553
13554        public final void addActivity(PackageParser.Activity a, String type) {
13555            mActivities.put(a.getComponentName(), a);
13556            if (DEBUG_SHOW_INFO)
13557                Log.v(
13558                TAG, "  " + type + " " +
13559                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13560            if (DEBUG_SHOW_INFO)
13561                Log.v(TAG, "    Class=" + a.info.name);
13562            final int NI = a.intents.size();
13563            for (int j=0; j<NI; j++) {
13564                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13565                if ("activity".equals(type)) {
13566                    final PackageSetting ps =
13567                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13568                    final List<PackageParser.Activity> systemActivities =
13569                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13570                    adjustPriority(systemActivities, intent);
13571                }
13572                if (DEBUG_SHOW_INFO) {
13573                    Log.v(TAG, "    IntentFilter:");
13574                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13575                }
13576                if (!intent.debugCheck()) {
13577                    Log.w(TAG, "==> For Activity " + a.info.name);
13578                }
13579                addFilter(intent);
13580            }
13581        }
13582
13583        public final void removeActivity(PackageParser.Activity a, String type) {
13584            mActivities.remove(a.getComponentName());
13585            if (DEBUG_SHOW_INFO) {
13586                Log.v(TAG, "  " + type + " "
13587                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13588                                : a.info.name) + ":");
13589                Log.v(TAG, "    Class=" + a.info.name);
13590            }
13591            final int NI = a.intents.size();
13592            for (int j=0; j<NI; j++) {
13593                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13594                if (DEBUG_SHOW_INFO) {
13595                    Log.v(TAG, "    IntentFilter:");
13596                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13597                }
13598                removeFilter(intent);
13599            }
13600        }
13601
13602        @Override
13603        protected boolean allowFilterResult(
13604                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13605            ActivityInfo filterAi = filter.activity.info;
13606            for (int i=dest.size()-1; i>=0; i--) {
13607                ActivityInfo destAi = dest.get(i).activityInfo;
13608                if (destAi.name == filterAi.name
13609                        && destAi.packageName == filterAi.packageName) {
13610                    return false;
13611                }
13612            }
13613            return true;
13614        }
13615
13616        @Override
13617        protected ActivityIntentInfo[] newArray(int size) {
13618            return new ActivityIntentInfo[size];
13619        }
13620
13621        @Override
13622        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13623            if (!sUserManager.exists(userId)) return true;
13624            PackageParser.Package p = filter.activity.owner;
13625            if (p != null) {
13626                PackageSetting ps = (PackageSetting)p.mExtras;
13627                if (ps != null) {
13628                    // System apps are never considered stopped for purposes of
13629                    // filtering, because there may be no way for the user to
13630                    // actually re-launch them.
13631                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13632                            && ps.getStopped(userId);
13633                }
13634            }
13635            return false;
13636        }
13637
13638        @Override
13639        protected boolean isPackageForFilter(String packageName,
13640                PackageParser.ActivityIntentInfo info) {
13641            return packageName.equals(info.activity.owner.packageName);
13642        }
13643
13644        @Override
13645        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13646                int match, int userId) {
13647            if (!sUserManager.exists(userId)) return null;
13648            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13649                return null;
13650            }
13651            final PackageParser.Activity activity = info.activity;
13652            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13653            if (ps == null) {
13654                return null;
13655            }
13656            final PackageUserState userState = ps.readUserState(userId);
13657            ActivityInfo ai =
13658                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13659            if (ai == null) {
13660                return null;
13661            }
13662            final boolean matchExplicitlyVisibleOnly =
13663                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13664            final boolean matchVisibleToInstantApp =
13665                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13666            final boolean componentVisible =
13667                    matchVisibleToInstantApp
13668                    && info.isVisibleToInstantApp()
13669                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13670            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13671            // throw out filters that aren't visible to ephemeral apps
13672            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13673                return null;
13674            }
13675            // throw out instant app filters if we're not explicitly requesting them
13676            if (!matchInstantApp && userState.instantApp) {
13677                return null;
13678            }
13679            // throw out instant app filters if updates are available; will trigger
13680            // instant app resolution
13681            if (userState.instantApp && ps.isUpdateAvailable()) {
13682                return null;
13683            }
13684            final ResolveInfo res = new ResolveInfo();
13685            res.activityInfo = ai;
13686            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13687                res.filter = info;
13688            }
13689            if (info != null) {
13690                res.handleAllWebDataURI = info.handleAllWebDataURI();
13691            }
13692            res.priority = info.getPriority();
13693            res.preferredOrder = activity.owner.mPreferredOrder;
13694            //System.out.println("Result: " + res.activityInfo.className +
13695            //                   " = " + res.priority);
13696            res.match = match;
13697            res.isDefault = info.hasDefault;
13698            res.labelRes = info.labelRes;
13699            res.nonLocalizedLabel = info.nonLocalizedLabel;
13700            if (userNeedsBadging(userId)) {
13701                res.noResourceId = true;
13702            } else {
13703                res.icon = info.icon;
13704            }
13705            res.iconResourceId = info.icon;
13706            res.system = res.activityInfo.applicationInfo.isSystemApp();
13707            res.isInstantAppAvailable = userState.instantApp;
13708            return res;
13709        }
13710
13711        @Override
13712        protected void sortResults(List<ResolveInfo> results) {
13713            Collections.sort(results, mResolvePrioritySorter);
13714        }
13715
13716        @Override
13717        protected void dumpFilter(PrintWriter out, String prefix,
13718                PackageParser.ActivityIntentInfo filter) {
13719            out.print(prefix); out.print(
13720                    Integer.toHexString(System.identityHashCode(filter.activity)));
13721                    out.print(' ');
13722                    filter.activity.printComponentShortName(out);
13723                    out.print(" filter ");
13724                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13725        }
13726
13727        @Override
13728        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13729            return filter.activity;
13730        }
13731
13732        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13733            PackageParser.Activity activity = (PackageParser.Activity)label;
13734            out.print(prefix); out.print(
13735                    Integer.toHexString(System.identityHashCode(activity)));
13736                    out.print(' ');
13737                    activity.printComponentShortName(out);
13738            if (count > 1) {
13739                out.print(" ("); out.print(count); out.print(" filters)");
13740            }
13741            out.println();
13742        }
13743
13744        // Keys are String (activity class name), values are Activity.
13745        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13746                = new ArrayMap<ComponentName, PackageParser.Activity>();
13747        private int mFlags;
13748    }
13749
13750    private final class ServiceIntentResolver
13751            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13752        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13753                boolean defaultOnly, int userId) {
13754            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13755            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13756        }
13757
13758        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13759                int userId) {
13760            if (!sUserManager.exists(userId)) return null;
13761            mFlags = flags;
13762            return super.queryIntent(intent, resolvedType,
13763                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13764                    userId);
13765        }
13766
13767        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13768                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13769            if (!sUserManager.exists(userId)) return null;
13770            if (packageServices == null) {
13771                return null;
13772            }
13773            mFlags = flags;
13774            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13775            final int N = packageServices.size();
13776            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13777                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13778
13779            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13780            for (int i = 0; i < N; ++i) {
13781                intentFilters = packageServices.get(i).intents;
13782                if (intentFilters != null && intentFilters.size() > 0) {
13783                    PackageParser.ServiceIntentInfo[] array =
13784                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13785                    intentFilters.toArray(array);
13786                    listCut.add(array);
13787                }
13788            }
13789            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13790        }
13791
13792        public final void addService(PackageParser.Service s) {
13793            mServices.put(s.getComponentName(), s);
13794            if (DEBUG_SHOW_INFO) {
13795                Log.v(TAG, "  "
13796                        + (s.info.nonLocalizedLabel != null
13797                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13798                Log.v(TAG, "    Class=" + s.info.name);
13799            }
13800            final int NI = s.intents.size();
13801            int j;
13802            for (j=0; j<NI; j++) {
13803                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13804                if (DEBUG_SHOW_INFO) {
13805                    Log.v(TAG, "    IntentFilter:");
13806                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13807                }
13808                if (!intent.debugCheck()) {
13809                    Log.w(TAG, "==> For Service " + s.info.name);
13810                }
13811                addFilter(intent);
13812            }
13813        }
13814
13815        public final void removeService(PackageParser.Service s) {
13816            mServices.remove(s.getComponentName());
13817            if (DEBUG_SHOW_INFO) {
13818                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13819                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13820                Log.v(TAG, "    Class=" + s.info.name);
13821            }
13822            final int NI = s.intents.size();
13823            int j;
13824            for (j=0; j<NI; j++) {
13825                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13826                if (DEBUG_SHOW_INFO) {
13827                    Log.v(TAG, "    IntentFilter:");
13828                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13829                }
13830                removeFilter(intent);
13831            }
13832        }
13833
13834        @Override
13835        protected boolean allowFilterResult(
13836                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13837            ServiceInfo filterSi = filter.service.info;
13838            for (int i=dest.size()-1; i>=0; i--) {
13839                ServiceInfo destAi = dest.get(i).serviceInfo;
13840                if (destAi.name == filterSi.name
13841                        && destAi.packageName == filterSi.packageName) {
13842                    return false;
13843                }
13844            }
13845            return true;
13846        }
13847
13848        @Override
13849        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13850            return new PackageParser.ServiceIntentInfo[size];
13851        }
13852
13853        @Override
13854        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13855            if (!sUserManager.exists(userId)) return true;
13856            PackageParser.Package p = filter.service.owner;
13857            if (p != null) {
13858                PackageSetting ps = (PackageSetting)p.mExtras;
13859                if (ps != null) {
13860                    // System apps are never considered stopped for purposes of
13861                    // filtering, because there may be no way for the user to
13862                    // actually re-launch them.
13863                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13864                            && ps.getStopped(userId);
13865                }
13866            }
13867            return false;
13868        }
13869
13870        @Override
13871        protected boolean isPackageForFilter(String packageName,
13872                PackageParser.ServiceIntentInfo info) {
13873            return packageName.equals(info.service.owner.packageName);
13874        }
13875
13876        @Override
13877        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13878                int match, int userId) {
13879            if (!sUserManager.exists(userId)) return null;
13880            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13881            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13882                return null;
13883            }
13884            final PackageParser.Service service = info.service;
13885            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13886            if (ps == null) {
13887                return null;
13888            }
13889            final PackageUserState userState = ps.readUserState(userId);
13890            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13891                    userState, userId);
13892            if (si == null) {
13893                return null;
13894            }
13895            final boolean matchVisibleToInstantApp =
13896                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13897            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13898            // throw out filters that aren't visible to ephemeral apps
13899            if (matchVisibleToInstantApp
13900                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13901                return null;
13902            }
13903            // throw out ephemeral filters if we're not explicitly requesting them
13904            if (!isInstantApp && userState.instantApp) {
13905                return null;
13906            }
13907            // throw out instant app filters if updates are available; will trigger
13908            // instant app resolution
13909            if (userState.instantApp && ps.isUpdateAvailable()) {
13910                return null;
13911            }
13912            final ResolveInfo res = new ResolveInfo();
13913            res.serviceInfo = si;
13914            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13915                res.filter = filter;
13916            }
13917            res.priority = info.getPriority();
13918            res.preferredOrder = service.owner.mPreferredOrder;
13919            res.match = match;
13920            res.isDefault = info.hasDefault;
13921            res.labelRes = info.labelRes;
13922            res.nonLocalizedLabel = info.nonLocalizedLabel;
13923            res.icon = info.icon;
13924            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13925            return res;
13926        }
13927
13928        @Override
13929        protected void sortResults(List<ResolveInfo> results) {
13930            Collections.sort(results, mResolvePrioritySorter);
13931        }
13932
13933        @Override
13934        protected void dumpFilter(PrintWriter out, String prefix,
13935                PackageParser.ServiceIntentInfo filter) {
13936            out.print(prefix); out.print(
13937                    Integer.toHexString(System.identityHashCode(filter.service)));
13938                    out.print(' ');
13939                    filter.service.printComponentShortName(out);
13940                    out.print(" filter ");
13941                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13942        }
13943
13944        @Override
13945        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13946            return filter.service;
13947        }
13948
13949        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13950            PackageParser.Service service = (PackageParser.Service)label;
13951            out.print(prefix); out.print(
13952                    Integer.toHexString(System.identityHashCode(service)));
13953                    out.print(' ');
13954                    service.printComponentShortName(out);
13955            if (count > 1) {
13956                out.print(" ("); out.print(count); out.print(" filters)");
13957            }
13958            out.println();
13959        }
13960
13961//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13962//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13963//            final List<ResolveInfo> retList = Lists.newArrayList();
13964//            while (i.hasNext()) {
13965//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13966//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13967//                    retList.add(resolveInfo);
13968//                }
13969//            }
13970//            return retList;
13971//        }
13972
13973        // Keys are String (activity class name), values are Activity.
13974        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13975                = new ArrayMap<ComponentName, PackageParser.Service>();
13976        private int mFlags;
13977    }
13978
13979    private final class ProviderIntentResolver
13980            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13981        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13982                boolean defaultOnly, int userId) {
13983            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13984            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13985        }
13986
13987        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13988                int userId) {
13989            if (!sUserManager.exists(userId))
13990                return null;
13991            mFlags = flags;
13992            return super.queryIntent(intent, resolvedType,
13993                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13994                    userId);
13995        }
13996
13997        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13998                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13999            if (!sUserManager.exists(userId))
14000                return null;
14001            if (packageProviders == null) {
14002                return null;
14003            }
14004            mFlags = flags;
14005            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14006            final int N = packageProviders.size();
14007            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14008                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14009
14010            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14011            for (int i = 0; i < N; ++i) {
14012                intentFilters = packageProviders.get(i).intents;
14013                if (intentFilters != null && intentFilters.size() > 0) {
14014                    PackageParser.ProviderIntentInfo[] array =
14015                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14016                    intentFilters.toArray(array);
14017                    listCut.add(array);
14018                }
14019            }
14020            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14021        }
14022
14023        public final void addProvider(PackageParser.Provider p) {
14024            if (mProviders.containsKey(p.getComponentName())) {
14025                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14026                return;
14027            }
14028
14029            mProviders.put(p.getComponentName(), p);
14030            if (DEBUG_SHOW_INFO) {
14031                Log.v(TAG, "  "
14032                        + (p.info.nonLocalizedLabel != null
14033                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14034                Log.v(TAG, "    Class=" + p.info.name);
14035            }
14036            final int NI = p.intents.size();
14037            int j;
14038            for (j = 0; j < NI; j++) {
14039                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14040                if (DEBUG_SHOW_INFO) {
14041                    Log.v(TAG, "    IntentFilter:");
14042                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14043                }
14044                if (!intent.debugCheck()) {
14045                    Log.w(TAG, "==> For Provider " + p.info.name);
14046                }
14047                addFilter(intent);
14048            }
14049        }
14050
14051        public final void removeProvider(PackageParser.Provider p) {
14052            mProviders.remove(p.getComponentName());
14053            if (DEBUG_SHOW_INFO) {
14054                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14055                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14056                Log.v(TAG, "    Class=" + p.info.name);
14057            }
14058            final int NI = p.intents.size();
14059            int j;
14060            for (j = 0; j < NI; j++) {
14061                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14062                if (DEBUG_SHOW_INFO) {
14063                    Log.v(TAG, "    IntentFilter:");
14064                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14065                }
14066                removeFilter(intent);
14067            }
14068        }
14069
14070        @Override
14071        protected boolean allowFilterResult(
14072                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14073            ProviderInfo filterPi = filter.provider.info;
14074            for (int i = dest.size() - 1; i >= 0; i--) {
14075                ProviderInfo destPi = dest.get(i).providerInfo;
14076                if (destPi.name == filterPi.name
14077                        && destPi.packageName == filterPi.packageName) {
14078                    return false;
14079                }
14080            }
14081            return true;
14082        }
14083
14084        @Override
14085        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14086            return new PackageParser.ProviderIntentInfo[size];
14087        }
14088
14089        @Override
14090        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14091            if (!sUserManager.exists(userId))
14092                return true;
14093            PackageParser.Package p = filter.provider.owner;
14094            if (p != null) {
14095                PackageSetting ps = (PackageSetting) p.mExtras;
14096                if (ps != null) {
14097                    // System apps are never considered stopped for purposes of
14098                    // filtering, because there may be no way for the user to
14099                    // actually re-launch them.
14100                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14101                            && ps.getStopped(userId);
14102                }
14103            }
14104            return false;
14105        }
14106
14107        @Override
14108        protected boolean isPackageForFilter(String packageName,
14109                PackageParser.ProviderIntentInfo info) {
14110            return packageName.equals(info.provider.owner.packageName);
14111        }
14112
14113        @Override
14114        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14115                int match, int userId) {
14116            if (!sUserManager.exists(userId))
14117                return null;
14118            final PackageParser.ProviderIntentInfo info = filter;
14119            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14120                return null;
14121            }
14122            final PackageParser.Provider provider = info.provider;
14123            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14124            if (ps == null) {
14125                return null;
14126            }
14127            final PackageUserState userState = ps.readUserState(userId);
14128            final boolean matchVisibleToInstantApp =
14129                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14130            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14131            // throw out filters that aren't visible to instant applications
14132            if (matchVisibleToInstantApp
14133                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14134                return null;
14135            }
14136            // throw out instant application filters if we're not explicitly requesting them
14137            if (!isInstantApp && userState.instantApp) {
14138                return null;
14139            }
14140            // throw out instant application filters if updates are available; will trigger
14141            // instant application resolution
14142            if (userState.instantApp && ps.isUpdateAvailable()) {
14143                return null;
14144            }
14145            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14146                    userState, userId);
14147            if (pi == null) {
14148                return null;
14149            }
14150            final ResolveInfo res = new ResolveInfo();
14151            res.providerInfo = pi;
14152            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14153                res.filter = filter;
14154            }
14155            res.priority = info.getPriority();
14156            res.preferredOrder = provider.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.providerInfo.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.ProviderIntentInfo filter) {
14174            out.print(prefix);
14175            out.print(
14176                    Integer.toHexString(System.identityHashCode(filter.provider)));
14177            out.print(' ');
14178            filter.provider.printComponentShortName(out);
14179            out.print(" filter ");
14180            out.println(Integer.toHexString(System.identityHashCode(filter)));
14181        }
14182
14183        @Override
14184        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14185            return filter.provider;
14186        }
14187
14188        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14189            PackageParser.Provider provider = (PackageParser.Provider)label;
14190            out.print(prefix); out.print(
14191                    Integer.toHexString(System.identityHashCode(provider)));
14192                    out.print(' ');
14193                    provider.printComponentShortName(out);
14194            if (count > 1) {
14195                out.print(" ("); out.print(count); out.print(" filters)");
14196            }
14197            out.println();
14198        }
14199
14200        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14201                = new ArrayMap<ComponentName, PackageParser.Provider>();
14202        private int mFlags;
14203    }
14204
14205    static final class EphemeralIntentResolver
14206            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14207        /**
14208         * The result that has the highest defined order. Ordering applies on a
14209         * per-package basis. Mapping is from package name to Pair of order and
14210         * EphemeralResolveInfo.
14211         * <p>
14212         * NOTE: This is implemented as a field variable for convenience and efficiency.
14213         * By having a field variable, we're able to track filter ordering as soon as
14214         * a non-zero order is defined. Otherwise, multiple loops across the result set
14215         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14216         * this needs to be contained entirely within {@link #filterResults}.
14217         */
14218        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14219
14220        @Override
14221        protected AuxiliaryResolveInfo[] newArray(int size) {
14222            return new AuxiliaryResolveInfo[size];
14223        }
14224
14225        @Override
14226        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14227            return true;
14228        }
14229
14230        @Override
14231        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14232                int userId) {
14233            if (!sUserManager.exists(userId)) {
14234                return null;
14235            }
14236            final String packageName = responseObj.resolveInfo.getPackageName();
14237            final Integer order = responseObj.getOrder();
14238            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14239                    mOrderResult.get(packageName);
14240            // ordering is enabled and this item's order isn't high enough
14241            if (lastOrderResult != null && lastOrderResult.first >= order) {
14242                return null;
14243            }
14244            final InstantAppResolveInfo res = responseObj.resolveInfo;
14245            if (order > 0) {
14246                // non-zero order, enable ordering
14247                mOrderResult.put(packageName, new Pair<>(order, res));
14248            }
14249            return responseObj;
14250        }
14251
14252        @Override
14253        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14254            // only do work if ordering is enabled [most of the time it won't be]
14255            if (mOrderResult.size() == 0) {
14256                return;
14257            }
14258            int resultSize = results.size();
14259            for (int i = 0; i < resultSize; i++) {
14260                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14261                final String packageName = info.getPackageName();
14262                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14263                if (savedInfo == null) {
14264                    // package doesn't having ordering
14265                    continue;
14266                }
14267                if (savedInfo.second == info) {
14268                    // circled back to the highest ordered item; remove from order list
14269                    mOrderResult.remove(savedInfo);
14270                    if (mOrderResult.size() == 0) {
14271                        // no more ordered items
14272                        break;
14273                    }
14274                    continue;
14275                }
14276                // item has a worse order, remove it from the result list
14277                results.remove(i);
14278                resultSize--;
14279                i--;
14280            }
14281        }
14282    }
14283
14284    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14285            new Comparator<ResolveInfo>() {
14286        public int compare(ResolveInfo r1, ResolveInfo r2) {
14287            int v1 = r1.priority;
14288            int v2 = r2.priority;
14289            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14290            if (v1 != v2) {
14291                return (v1 > v2) ? -1 : 1;
14292            }
14293            v1 = r1.preferredOrder;
14294            v2 = r2.preferredOrder;
14295            if (v1 != v2) {
14296                return (v1 > v2) ? -1 : 1;
14297            }
14298            if (r1.isDefault != r2.isDefault) {
14299                return r1.isDefault ? -1 : 1;
14300            }
14301            v1 = r1.match;
14302            v2 = r2.match;
14303            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14304            if (v1 != v2) {
14305                return (v1 > v2) ? -1 : 1;
14306            }
14307            if (r1.system != r2.system) {
14308                return r1.system ? -1 : 1;
14309            }
14310            if (r1.activityInfo != null) {
14311                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14312            }
14313            if (r1.serviceInfo != null) {
14314                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14315            }
14316            if (r1.providerInfo != null) {
14317                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14318            }
14319            return 0;
14320        }
14321    };
14322
14323    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14324            new Comparator<ProviderInfo>() {
14325        public int compare(ProviderInfo p1, ProviderInfo p2) {
14326            final int v1 = p1.initOrder;
14327            final int v2 = p2.initOrder;
14328            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14329        }
14330    };
14331
14332    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14333            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14334            final int[] userIds) {
14335        mHandler.post(new Runnable() {
14336            @Override
14337            public void run() {
14338                try {
14339                    final IActivityManager am = ActivityManager.getService();
14340                    if (am == null) return;
14341                    final int[] resolvedUserIds;
14342                    if (userIds == null) {
14343                        resolvedUserIds = am.getRunningUserIds();
14344                    } else {
14345                        resolvedUserIds = userIds;
14346                    }
14347                    for (int id : resolvedUserIds) {
14348                        final Intent intent = new Intent(action,
14349                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14350                        if (extras != null) {
14351                            intent.putExtras(extras);
14352                        }
14353                        if (targetPkg != null) {
14354                            intent.setPackage(targetPkg);
14355                        }
14356                        // Modify the UID when posting to other users
14357                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14358                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14359                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14360                            intent.putExtra(Intent.EXTRA_UID, uid);
14361                        }
14362                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14363                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14364                        if (DEBUG_BROADCASTS) {
14365                            RuntimeException here = new RuntimeException("here");
14366                            here.fillInStackTrace();
14367                            Slog.d(TAG, "Sending to user " + id + ": "
14368                                    + intent.toShortString(false, true, false, false)
14369                                    + " " + intent.getExtras(), here);
14370                        }
14371                        am.broadcastIntent(null, intent, null, finishedReceiver,
14372                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14373                                null, finishedReceiver != null, false, id);
14374                    }
14375                } catch (RemoteException ex) {
14376                }
14377            }
14378        });
14379    }
14380
14381    /**
14382     * Check if the external storage media is available. This is true if there
14383     * is a mounted external storage medium or if the external storage is
14384     * emulated.
14385     */
14386    private boolean isExternalMediaAvailable() {
14387        return mMediaMounted || Environment.isExternalStorageEmulated();
14388    }
14389
14390    @Override
14391    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14392        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14393            return null;
14394        }
14395        // writer
14396        synchronized (mPackages) {
14397            if (!isExternalMediaAvailable()) {
14398                // If the external storage is no longer mounted at this point,
14399                // the caller may not have been able to delete all of this
14400                // packages files and can not delete any more.  Bail.
14401                return null;
14402            }
14403            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14404            if (lastPackage != null) {
14405                pkgs.remove(lastPackage);
14406            }
14407            if (pkgs.size() > 0) {
14408                return pkgs.get(0);
14409            }
14410        }
14411        return null;
14412    }
14413
14414    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14415        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14416                userId, andCode ? 1 : 0, packageName);
14417        if (mSystemReady) {
14418            msg.sendToTarget();
14419        } else {
14420            if (mPostSystemReadyMessages == null) {
14421                mPostSystemReadyMessages = new ArrayList<>();
14422            }
14423            mPostSystemReadyMessages.add(msg);
14424        }
14425    }
14426
14427    void startCleaningPackages() {
14428        // reader
14429        if (!isExternalMediaAvailable()) {
14430            return;
14431        }
14432        synchronized (mPackages) {
14433            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14434                return;
14435            }
14436        }
14437        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14438        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14439        IActivityManager am = ActivityManager.getService();
14440        if (am != null) {
14441            int dcsUid = -1;
14442            synchronized (mPackages) {
14443                if (!mDefaultContainerWhitelisted) {
14444                    mDefaultContainerWhitelisted = true;
14445                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14446                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14447                }
14448            }
14449            try {
14450                if (dcsUid > 0) {
14451                    am.backgroundWhitelistUid(dcsUid);
14452                }
14453                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14454                        UserHandle.USER_SYSTEM);
14455            } catch (RemoteException e) {
14456            }
14457        }
14458    }
14459
14460    @Override
14461    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14462            int installFlags, String installerPackageName, int userId) {
14463        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14464
14465        final int callingUid = Binder.getCallingUid();
14466        enforceCrossUserPermission(callingUid, userId,
14467                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14468
14469        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14470            try {
14471                if (observer != null) {
14472                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14473                }
14474            } catch (RemoteException re) {
14475            }
14476            return;
14477        }
14478
14479        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14480            installFlags |= PackageManager.INSTALL_FROM_ADB;
14481
14482        } else {
14483            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14484            // about installerPackageName.
14485
14486            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14487            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14488        }
14489
14490        UserHandle user;
14491        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14492            user = UserHandle.ALL;
14493        } else {
14494            user = new UserHandle(userId);
14495        }
14496
14497        // Only system components can circumvent runtime permissions when installing.
14498        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14499                && mContext.checkCallingOrSelfPermission(Manifest.permission
14500                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14501            throw new SecurityException("You need the "
14502                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14503                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14504        }
14505
14506        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14507                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14508            throw new IllegalArgumentException(
14509                    "New installs into ASEC containers no longer supported");
14510        }
14511
14512        final File originFile = new File(originPath);
14513        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14514
14515        final Message msg = mHandler.obtainMessage(INIT_COPY);
14516        final VerificationInfo verificationInfo = new VerificationInfo(
14517                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14518        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14519                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14520                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14521                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14522        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14523        msg.obj = params;
14524
14525        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14526                System.identityHashCode(msg.obj));
14527        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14528                System.identityHashCode(msg.obj));
14529
14530        mHandler.sendMessage(msg);
14531    }
14532
14533
14534    /**
14535     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14536     * it is acting on behalf on an enterprise or the user).
14537     *
14538     * Note that the ordering of the conditionals in this method is important. The checks we perform
14539     * are as follows, in this order:
14540     *
14541     * 1) If the install is being performed by a system app, we can trust the app to have set the
14542     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14543     *    what it is.
14544     * 2) If the install is being performed by a device or profile owner app, the install reason
14545     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14546     *    set the install reason correctly. If the app targets an older SDK version where install
14547     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14548     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14549     * 3) In all other cases, the install is being performed by a regular app that is neither part
14550     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14551     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14552     *    set to enterprise policy and if so, change it to unknown instead.
14553     */
14554    private int fixUpInstallReason(String installerPackageName, int installerUid,
14555            int installReason) {
14556        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14557                == PERMISSION_GRANTED) {
14558            // If the install is being performed by a system app, we trust that app to have set the
14559            // install reason correctly.
14560            return installReason;
14561        }
14562
14563        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14564            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14565        if (dpm != null) {
14566            ComponentName owner = null;
14567            try {
14568                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14569                if (owner == null) {
14570                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14571                }
14572            } catch (RemoteException e) {
14573            }
14574            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14575                // If the install is being performed by a device or profile owner, the install
14576                // reason should be enterprise policy.
14577                return PackageManager.INSTALL_REASON_POLICY;
14578            }
14579        }
14580
14581        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14582            // If the install is being performed by a regular app (i.e. neither system app nor
14583            // device or profile owner), we have no reason to believe that the app is acting on
14584            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14585            // change it to unknown instead.
14586            return PackageManager.INSTALL_REASON_UNKNOWN;
14587        }
14588
14589        // If the install is being performed by a regular app and the install reason was set to any
14590        // value but enterprise policy, leave the install reason unchanged.
14591        return installReason;
14592    }
14593
14594    void installStage(String packageName, File stagedDir, String stagedCid,
14595            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14596            String installerPackageName, int installerUid, UserHandle user,
14597            Certificate[][] certificates) {
14598        if (DEBUG_EPHEMERAL) {
14599            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14600                Slog.d(TAG, "Ephemeral install of " + packageName);
14601            }
14602        }
14603        final VerificationInfo verificationInfo = new VerificationInfo(
14604                sessionParams.originatingUri, sessionParams.referrerUri,
14605                sessionParams.originatingUid, installerUid);
14606
14607        final OriginInfo origin;
14608        if (stagedDir != null) {
14609            origin = OriginInfo.fromStagedFile(stagedDir);
14610        } else {
14611            origin = OriginInfo.fromStagedContainer(stagedCid);
14612        }
14613
14614        final Message msg = mHandler.obtainMessage(INIT_COPY);
14615        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14616                sessionParams.installReason);
14617        final InstallParams params = new InstallParams(origin, null, observer,
14618                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14619                verificationInfo, user, sessionParams.abiOverride,
14620                sessionParams.grantedRuntimePermissions, certificates, installReason);
14621        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14622        msg.obj = params;
14623
14624        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14625                System.identityHashCode(msg.obj));
14626        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14627                System.identityHashCode(msg.obj));
14628
14629        mHandler.sendMessage(msg);
14630    }
14631
14632    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14633            int userId) {
14634        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14635        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14636                false /*startReceiver*/, pkgSetting.appId, userId);
14637
14638        // Send a session commit broadcast
14639        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14640        info.installReason = pkgSetting.getInstallReason(userId);
14641        info.appPackageName = packageName;
14642        sendSessionCommitBroadcast(info, userId);
14643    }
14644
14645    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14646            boolean includeStopped, int appId, int... userIds) {
14647        if (ArrayUtils.isEmpty(userIds)) {
14648            return;
14649        }
14650        Bundle extras = new Bundle(1);
14651        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14652        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14653
14654        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14655                packageName, extras, 0, null, null, userIds);
14656        if (sendBootCompleted) {
14657            mHandler.post(() -> {
14658                        for (int userId : userIds) {
14659                            sendBootCompletedBroadcastToSystemApp(
14660                                    packageName, includeStopped, userId);
14661                        }
14662                    }
14663            );
14664        }
14665    }
14666
14667    /**
14668     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14669     * automatically without needing an explicit launch.
14670     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14671     */
14672    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14673            int userId) {
14674        // If user is not running, the app didn't miss any broadcast
14675        if (!mUserManagerInternal.isUserRunning(userId)) {
14676            return;
14677        }
14678        final IActivityManager am = ActivityManager.getService();
14679        try {
14680            // Deliver LOCKED_BOOT_COMPLETED first
14681            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14682                    .setPackage(packageName);
14683            if (includeStopped) {
14684                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14685            }
14686            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14687            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14688                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14689
14690            // Deliver BOOT_COMPLETED only if user is unlocked
14691            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14692                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14693                if (includeStopped) {
14694                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14695                }
14696                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14697                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14698            }
14699        } catch (RemoteException e) {
14700            throw e.rethrowFromSystemServer();
14701        }
14702    }
14703
14704    @Override
14705    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14706            int userId) {
14707        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14708        PackageSetting pkgSetting;
14709        final int callingUid = Binder.getCallingUid();
14710        enforceCrossUserPermission(callingUid, userId,
14711                true /* requireFullPermission */, true /* checkShell */,
14712                "setApplicationHiddenSetting for user " + userId);
14713
14714        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14715            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14716            return false;
14717        }
14718
14719        long callingId = Binder.clearCallingIdentity();
14720        try {
14721            boolean sendAdded = false;
14722            boolean sendRemoved = false;
14723            // writer
14724            synchronized (mPackages) {
14725                pkgSetting = mSettings.mPackages.get(packageName);
14726                if (pkgSetting == null) {
14727                    return false;
14728                }
14729                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14730                    return false;
14731                }
14732                // Do not allow "android" is being disabled
14733                if ("android".equals(packageName)) {
14734                    Slog.w(TAG, "Cannot hide package: android");
14735                    return false;
14736                }
14737                // Cannot hide static shared libs as they are considered
14738                // a part of the using app (emulating static linking). Also
14739                // static libs are installed always on internal storage.
14740                PackageParser.Package pkg = mPackages.get(packageName);
14741                if (pkg != null && pkg.staticSharedLibName != null) {
14742                    Slog.w(TAG, "Cannot hide package: " + packageName
14743                            + " providing static shared library: "
14744                            + pkg.staticSharedLibName);
14745                    return false;
14746                }
14747                // Only allow protected packages to hide themselves.
14748                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14749                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14750                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14751                    return false;
14752                }
14753
14754                if (pkgSetting.getHidden(userId) != hidden) {
14755                    pkgSetting.setHidden(hidden, userId);
14756                    mSettings.writePackageRestrictionsLPr(userId);
14757                    if (hidden) {
14758                        sendRemoved = true;
14759                    } else {
14760                        sendAdded = true;
14761                    }
14762                }
14763            }
14764            if (sendAdded) {
14765                sendPackageAddedForUser(packageName, pkgSetting, userId);
14766                return true;
14767            }
14768            if (sendRemoved) {
14769                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14770                        "hiding pkg");
14771                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14772                return true;
14773            }
14774        } finally {
14775            Binder.restoreCallingIdentity(callingId);
14776        }
14777        return false;
14778    }
14779
14780    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14781            int userId) {
14782        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14783        info.removedPackage = packageName;
14784        info.installerPackageName = pkgSetting.installerPackageName;
14785        info.removedUsers = new int[] {userId};
14786        info.broadcastUsers = new int[] {userId};
14787        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14788        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14789    }
14790
14791    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14792        if (pkgList.length > 0) {
14793            Bundle extras = new Bundle(1);
14794            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14795
14796            sendPackageBroadcast(
14797                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14798                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14799                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14800                    new int[] {userId});
14801        }
14802    }
14803
14804    /**
14805     * Returns true if application is not found or there was an error. Otherwise it returns
14806     * the hidden state of the package for the given user.
14807     */
14808    @Override
14809    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14810        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14811        final int callingUid = Binder.getCallingUid();
14812        enforceCrossUserPermission(callingUid, userId,
14813                true /* requireFullPermission */, false /* checkShell */,
14814                "getApplicationHidden for user " + userId);
14815        PackageSetting ps;
14816        long callingId = Binder.clearCallingIdentity();
14817        try {
14818            // writer
14819            synchronized (mPackages) {
14820                ps = mSettings.mPackages.get(packageName);
14821                if (ps == null) {
14822                    return true;
14823                }
14824                if (filterAppAccessLPr(ps, callingUid, userId)) {
14825                    return true;
14826                }
14827                return ps.getHidden(userId);
14828            }
14829        } finally {
14830            Binder.restoreCallingIdentity(callingId);
14831        }
14832    }
14833
14834    /**
14835     * @hide
14836     */
14837    @Override
14838    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14839            int installReason) {
14840        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14841                null);
14842        PackageSetting pkgSetting;
14843        final int callingUid = Binder.getCallingUid();
14844        enforceCrossUserPermission(callingUid, userId,
14845                true /* requireFullPermission */, true /* checkShell */,
14846                "installExistingPackage for user " + userId);
14847        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14848            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14849        }
14850
14851        long callingId = Binder.clearCallingIdentity();
14852        try {
14853            boolean installed = false;
14854            final boolean instantApp =
14855                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14856            final boolean fullApp =
14857                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14858
14859            // writer
14860            synchronized (mPackages) {
14861                pkgSetting = mSettings.mPackages.get(packageName);
14862                if (pkgSetting == null) {
14863                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14864                }
14865                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14866                    // only allow the existing package to be used if it's installed as a full
14867                    // application for at least one user
14868                    boolean installAllowed = false;
14869                    for (int checkUserId : sUserManager.getUserIds()) {
14870                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14871                        if (installAllowed) {
14872                            break;
14873                        }
14874                    }
14875                    if (!installAllowed) {
14876                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14877                    }
14878                }
14879                if (!pkgSetting.getInstalled(userId)) {
14880                    pkgSetting.setInstalled(true, userId);
14881                    pkgSetting.setHidden(false, userId);
14882                    pkgSetting.setInstallReason(installReason, userId);
14883                    mSettings.writePackageRestrictionsLPr(userId);
14884                    mSettings.writeKernelMappingLPr(pkgSetting);
14885                    installed = true;
14886                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14887                    // upgrade app from instant to full; we don't allow app downgrade
14888                    installed = true;
14889                }
14890                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14891            }
14892
14893            if (installed) {
14894                if (pkgSetting.pkg != null) {
14895                    synchronized (mInstallLock) {
14896                        // We don't need to freeze for a brand new install
14897                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14898                    }
14899                }
14900                sendPackageAddedForUser(packageName, pkgSetting, userId);
14901                synchronized (mPackages) {
14902                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14903                }
14904            }
14905        } finally {
14906            Binder.restoreCallingIdentity(callingId);
14907        }
14908
14909        return PackageManager.INSTALL_SUCCEEDED;
14910    }
14911
14912    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14913            boolean instantApp, boolean fullApp) {
14914        // no state specified; do nothing
14915        if (!instantApp && !fullApp) {
14916            return;
14917        }
14918        if (userId != UserHandle.USER_ALL) {
14919            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14920                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14921            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14922                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14923            }
14924        } else {
14925            for (int currentUserId : sUserManager.getUserIds()) {
14926                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14927                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14928                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14929                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14930                }
14931            }
14932        }
14933    }
14934
14935    boolean isUserRestricted(int userId, String restrictionKey) {
14936        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14937        if (restrictions.getBoolean(restrictionKey, false)) {
14938            Log.w(TAG, "User is restricted: " + restrictionKey);
14939            return true;
14940        }
14941        return false;
14942    }
14943
14944    @Override
14945    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14946            int userId) {
14947        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14948        final int callingUid = Binder.getCallingUid();
14949        enforceCrossUserPermission(callingUid, userId,
14950                true /* requireFullPermission */, true /* checkShell */,
14951                "setPackagesSuspended for user " + userId);
14952
14953        if (ArrayUtils.isEmpty(packageNames)) {
14954            return packageNames;
14955        }
14956
14957        // List of package names for whom the suspended state has changed.
14958        List<String> changedPackages = new ArrayList<>(packageNames.length);
14959        // List of package names for whom the suspended state is not set as requested in this
14960        // method.
14961        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14962        long callingId = Binder.clearCallingIdentity();
14963        try {
14964            for (int i = 0; i < packageNames.length; i++) {
14965                String packageName = packageNames[i];
14966                boolean changed = false;
14967                final int appId;
14968                synchronized (mPackages) {
14969                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14970                    if (pkgSetting == null
14971                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14972                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14973                                + "\". Skipping suspending/un-suspending.");
14974                        unactionedPackages.add(packageName);
14975                        continue;
14976                    }
14977                    appId = pkgSetting.appId;
14978                    if (pkgSetting.getSuspended(userId) != suspended) {
14979                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14980                            unactionedPackages.add(packageName);
14981                            continue;
14982                        }
14983                        pkgSetting.setSuspended(suspended, userId);
14984                        mSettings.writePackageRestrictionsLPr(userId);
14985                        changed = true;
14986                        changedPackages.add(packageName);
14987                    }
14988                }
14989
14990                if (changed && suspended) {
14991                    killApplication(packageName, UserHandle.getUid(userId, appId),
14992                            "suspending package");
14993                }
14994            }
14995        } finally {
14996            Binder.restoreCallingIdentity(callingId);
14997        }
14998
14999        if (!changedPackages.isEmpty()) {
15000            sendPackagesSuspendedForUser(changedPackages.toArray(
15001                    new String[changedPackages.size()]), userId, suspended);
15002        }
15003
15004        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15005    }
15006
15007    @Override
15008    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15009        final int callingUid = Binder.getCallingUid();
15010        enforceCrossUserPermission(callingUid, userId,
15011                true /* requireFullPermission */, false /* checkShell */,
15012                "isPackageSuspendedForUser for user " + userId);
15013        synchronized (mPackages) {
15014            final PackageSetting ps = mSettings.mPackages.get(packageName);
15015            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15016                throw new IllegalArgumentException("Unknown target package: " + packageName);
15017            }
15018            return ps.getSuspended(userId);
15019        }
15020    }
15021
15022    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15023        if (isPackageDeviceAdmin(packageName, userId)) {
15024            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15025                    + "\": has an active device admin");
15026            return false;
15027        }
15028
15029        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15030        if (packageName.equals(activeLauncherPackageName)) {
15031            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15032                    + "\": contains the active launcher");
15033            return false;
15034        }
15035
15036        if (packageName.equals(mRequiredInstallerPackage)) {
15037            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15038                    + "\": required for package installation");
15039            return false;
15040        }
15041
15042        if (packageName.equals(mRequiredUninstallerPackage)) {
15043            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15044                    + "\": required for package uninstallation");
15045            return false;
15046        }
15047
15048        if (packageName.equals(mRequiredVerifierPackage)) {
15049            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15050                    + "\": required for package verification");
15051            return false;
15052        }
15053
15054        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15055            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15056                    + "\": is the default dialer");
15057            return false;
15058        }
15059
15060        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15061            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15062                    + "\": protected package");
15063            return false;
15064        }
15065
15066        // Cannot suspend static shared libs as they are considered
15067        // a part of the using app (emulating static linking). Also
15068        // static libs are installed always on internal storage.
15069        PackageParser.Package pkg = mPackages.get(packageName);
15070        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15071            Slog.w(TAG, "Cannot suspend package: " + packageName
15072                    + " providing static shared library: "
15073                    + pkg.staticSharedLibName);
15074            return false;
15075        }
15076
15077        return true;
15078    }
15079
15080    private String getActiveLauncherPackageName(int userId) {
15081        Intent intent = new Intent(Intent.ACTION_MAIN);
15082        intent.addCategory(Intent.CATEGORY_HOME);
15083        ResolveInfo resolveInfo = resolveIntent(
15084                intent,
15085                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15086                PackageManager.MATCH_DEFAULT_ONLY,
15087                userId);
15088
15089        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15090    }
15091
15092    private String getDefaultDialerPackageName(int userId) {
15093        synchronized (mPackages) {
15094            return mSettings.getDefaultDialerPackageNameLPw(userId);
15095        }
15096    }
15097
15098    @Override
15099    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15100        mContext.enforceCallingOrSelfPermission(
15101                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15102                "Only package verification agents can verify applications");
15103
15104        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15105        final PackageVerificationResponse response = new PackageVerificationResponse(
15106                verificationCode, Binder.getCallingUid());
15107        msg.arg1 = id;
15108        msg.obj = response;
15109        mHandler.sendMessage(msg);
15110    }
15111
15112    @Override
15113    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15114            long millisecondsToDelay) {
15115        mContext.enforceCallingOrSelfPermission(
15116                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15117                "Only package verification agents can extend verification timeouts");
15118
15119        final PackageVerificationState state = mPendingVerification.get(id);
15120        final PackageVerificationResponse response = new PackageVerificationResponse(
15121                verificationCodeAtTimeout, Binder.getCallingUid());
15122
15123        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15124            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15125        }
15126        if (millisecondsToDelay < 0) {
15127            millisecondsToDelay = 0;
15128        }
15129        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15130                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15131            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15132        }
15133
15134        if ((state != null) && !state.timeoutExtended()) {
15135            state.extendTimeout();
15136
15137            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15138            msg.arg1 = id;
15139            msg.obj = response;
15140            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15141        }
15142    }
15143
15144    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15145            int verificationCode, UserHandle user) {
15146        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15147        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15148        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15149        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15150        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15151
15152        mContext.sendBroadcastAsUser(intent, user,
15153                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15154    }
15155
15156    private ComponentName matchComponentForVerifier(String packageName,
15157            List<ResolveInfo> receivers) {
15158        ActivityInfo targetReceiver = null;
15159
15160        final int NR = receivers.size();
15161        for (int i = 0; i < NR; i++) {
15162            final ResolveInfo info = receivers.get(i);
15163            if (info.activityInfo == null) {
15164                continue;
15165            }
15166
15167            if (packageName.equals(info.activityInfo.packageName)) {
15168                targetReceiver = info.activityInfo;
15169                break;
15170            }
15171        }
15172
15173        if (targetReceiver == null) {
15174            return null;
15175        }
15176
15177        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15178    }
15179
15180    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15181            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15182        if (pkgInfo.verifiers.length == 0) {
15183            return null;
15184        }
15185
15186        final int N = pkgInfo.verifiers.length;
15187        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15188        for (int i = 0; i < N; i++) {
15189            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15190
15191            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15192                    receivers);
15193            if (comp == null) {
15194                continue;
15195            }
15196
15197            final int verifierUid = getUidForVerifier(verifierInfo);
15198            if (verifierUid == -1) {
15199                continue;
15200            }
15201
15202            if (DEBUG_VERIFY) {
15203                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15204                        + " with the correct signature");
15205            }
15206            sufficientVerifiers.add(comp);
15207            verificationState.addSufficientVerifier(verifierUid);
15208        }
15209
15210        return sufficientVerifiers;
15211    }
15212
15213    private int getUidForVerifier(VerifierInfo verifierInfo) {
15214        synchronized (mPackages) {
15215            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15216            if (pkg == null) {
15217                return -1;
15218            } else if (pkg.mSignatures.length != 1) {
15219                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15220                        + " has more than one signature; ignoring");
15221                return -1;
15222            }
15223
15224            /*
15225             * If the public key of the package's signature does not match
15226             * our expected public key, then this is a different package and
15227             * we should skip.
15228             */
15229
15230            final byte[] expectedPublicKey;
15231            try {
15232                final Signature verifierSig = pkg.mSignatures[0];
15233                final PublicKey publicKey = verifierSig.getPublicKey();
15234                expectedPublicKey = publicKey.getEncoded();
15235            } catch (CertificateException e) {
15236                return -1;
15237            }
15238
15239            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15240
15241            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15242                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15243                        + " does not have the expected public key; ignoring");
15244                return -1;
15245            }
15246
15247            return pkg.applicationInfo.uid;
15248        }
15249    }
15250
15251    @Override
15252    public void finishPackageInstall(int token, boolean didLaunch) {
15253        enforceSystemOrRoot("Only the system is allowed to finish installs");
15254
15255        if (DEBUG_INSTALL) {
15256            Slog.v(TAG, "BM finishing package install for " + token);
15257        }
15258        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15259
15260        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15261        mHandler.sendMessage(msg);
15262    }
15263
15264    /**
15265     * Get the verification agent timeout.  Used for both the APK verifier and the
15266     * intent filter verifier.
15267     *
15268     * @return verification timeout in milliseconds
15269     */
15270    private long getVerificationTimeout() {
15271        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15272                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15273                DEFAULT_VERIFICATION_TIMEOUT);
15274    }
15275
15276    /**
15277     * Get the default verification agent response code.
15278     *
15279     * @return default verification response code
15280     */
15281    private int getDefaultVerificationResponse(UserHandle user) {
15282        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15283            return PackageManager.VERIFICATION_REJECT;
15284        }
15285        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15286                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15287                DEFAULT_VERIFICATION_RESPONSE);
15288    }
15289
15290    /**
15291     * Check whether or not package verification has been enabled.
15292     *
15293     * @return true if verification should be performed
15294     */
15295    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15296        if (!DEFAULT_VERIFY_ENABLE) {
15297            return false;
15298        }
15299
15300        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15301
15302        // Check if installing from ADB
15303        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15304            // Do not run verification in a test harness environment
15305            if (ActivityManager.isRunningInTestHarness()) {
15306                return false;
15307            }
15308            if (ensureVerifyAppsEnabled) {
15309                return true;
15310            }
15311            // Check if the developer does not want package verification for ADB installs
15312            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15313                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15314                return false;
15315            }
15316        } else {
15317            // only when not installed from ADB, skip verification for instant apps when
15318            // the installer and verifier are the same.
15319            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15320                if (mInstantAppInstallerActivity != null
15321                        && mInstantAppInstallerActivity.packageName.equals(
15322                                mRequiredVerifierPackage)) {
15323                    try {
15324                        mContext.getSystemService(AppOpsManager.class)
15325                                .checkPackage(installerUid, mRequiredVerifierPackage);
15326                        if (DEBUG_VERIFY) {
15327                            Slog.i(TAG, "disable verification for instant app");
15328                        }
15329                        return false;
15330                    } catch (SecurityException ignore) { }
15331                }
15332            }
15333        }
15334
15335        if (ensureVerifyAppsEnabled) {
15336            return true;
15337        }
15338
15339        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15340                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15341    }
15342
15343    @Override
15344    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15345            throws RemoteException {
15346        mContext.enforceCallingOrSelfPermission(
15347                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15348                "Only intentfilter verification agents can verify applications");
15349
15350        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15351        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15352                Binder.getCallingUid(), verificationCode, failedDomains);
15353        msg.arg1 = id;
15354        msg.obj = response;
15355        mHandler.sendMessage(msg);
15356    }
15357
15358    @Override
15359    public int getIntentVerificationStatus(String packageName, int userId) {
15360        final int callingUid = Binder.getCallingUid();
15361        if (UserHandle.getUserId(callingUid) != userId) {
15362            mContext.enforceCallingOrSelfPermission(
15363                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15364                    "getIntentVerificationStatus" + userId);
15365        }
15366        if (getInstantAppPackageName(callingUid) != null) {
15367            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15368        }
15369        synchronized (mPackages) {
15370            final PackageSetting ps = mSettings.mPackages.get(packageName);
15371            if (ps == null
15372                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15373                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15374            }
15375            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15376        }
15377    }
15378
15379    @Override
15380    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15381        mContext.enforceCallingOrSelfPermission(
15382                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15383
15384        boolean result = false;
15385        synchronized (mPackages) {
15386            final PackageSetting ps = mSettings.mPackages.get(packageName);
15387            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15388                return false;
15389            }
15390            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15391        }
15392        if (result) {
15393            scheduleWritePackageRestrictionsLocked(userId);
15394        }
15395        return result;
15396    }
15397
15398    @Override
15399    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15400            String packageName) {
15401        final int callingUid = Binder.getCallingUid();
15402        if (getInstantAppPackageName(callingUid) != null) {
15403            return ParceledListSlice.emptyList();
15404        }
15405        synchronized (mPackages) {
15406            final PackageSetting ps = mSettings.mPackages.get(packageName);
15407            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15408                return ParceledListSlice.emptyList();
15409            }
15410            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15411        }
15412    }
15413
15414    @Override
15415    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15416        if (TextUtils.isEmpty(packageName)) {
15417            return ParceledListSlice.emptyList();
15418        }
15419        final int callingUid = Binder.getCallingUid();
15420        final int callingUserId = UserHandle.getUserId(callingUid);
15421        synchronized (mPackages) {
15422            PackageParser.Package pkg = mPackages.get(packageName);
15423            if (pkg == null || pkg.activities == null) {
15424                return ParceledListSlice.emptyList();
15425            }
15426            if (pkg.mExtras == null) {
15427                return ParceledListSlice.emptyList();
15428            }
15429            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15430            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15431                return ParceledListSlice.emptyList();
15432            }
15433            final int count = pkg.activities.size();
15434            ArrayList<IntentFilter> result = new ArrayList<>();
15435            for (int n=0; n<count; n++) {
15436                PackageParser.Activity activity = pkg.activities.get(n);
15437                if (activity.intents != null && activity.intents.size() > 0) {
15438                    result.addAll(activity.intents);
15439                }
15440            }
15441            return new ParceledListSlice<>(result);
15442        }
15443    }
15444
15445    @Override
15446    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15447        mContext.enforceCallingOrSelfPermission(
15448                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15449        if (UserHandle.getCallingUserId() != userId) {
15450            mContext.enforceCallingOrSelfPermission(
15451                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15452        }
15453
15454        synchronized (mPackages) {
15455            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15456            if (packageName != null) {
15457                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15458                        packageName, userId);
15459            }
15460            return result;
15461        }
15462    }
15463
15464    @Override
15465    public String getDefaultBrowserPackageName(int userId) {
15466        if (UserHandle.getCallingUserId() != userId) {
15467            mContext.enforceCallingOrSelfPermission(
15468                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15469        }
15470        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15471            return null;
15472        }
15473        synchronized (mPackages) {
15474            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15475        }
15476    }
15477
15478    /**
15479     * Get the "allow unknown sources" setting.
15480     *
15481     * @return the current "allow unknown sources" setting
15482     */
15483    private int getUnknownSourcesSettings() {
15484        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15485                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15486                -1);
15487    }
15488
15489    @Override
15490    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15491        final int callingUid = Binder.getCallingUid();
15492        if (getInstantAppPackageName(callingUid) != null) {
15493            return;
15494        }
15495        // writer
15496        synchronized (mPackages) {
15497            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15498            if (targetPackageSetting == null
15499                    || filterAppAccessLPr(
15500                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15501                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15502            }
15503
15504            PackageSetting installerPackageSetting;
15505            if (installerPackageName != null) {
15506                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15507                if (installerPackageSetting == null) {
15508                    throw new IllegalArgumentException("Unknown installer package: "
15509                            + installerPackageName);
15510                }
15511            } else {
15512                installerPackageSetting = null;
15513            }
15514
15515            Signature[] callerSignature;
15516            Object obj = mSettings.getUserIdLPr(callingUid);
15517            if (obj != null) {
15518                if (obj instanceof SharedUserSetting) {
15519                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15520                } else if (obj instanceof PackageSetting) {
15521                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15522                } else {
15523                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15524                }
15525            } else {
15526                throw new SecurityException("Unknown calling UID: " + callingUid);
15527            }
15528
15529            // Verify: can't set installerPackageName to a package that is
15530            // not signed with the same cert as the caller.
15531            if (installerPackageSetting != null) {
15532                if (compareSignatures(callerSignature,
15533                        installerPackageSetting.signatures.mSignatures)
15534                        != PackageManager.SIGNATURE_MATCH) {
15535                    throw new SecurityException(
15536                            "Caller does not have same cert as new installer package "
15537                            + installerPackageName);
15538                }
15539            }
15540
15541            // Verify: if target already has an installer package, it must
15542            // be signed with the same cert as the caller.
15543            if (targetPackageSetting.installerPackageName != null) {
15544                PackageSetting setting = mSettings.mPackages.get(
15545                        targetPackageSetting.installerPackageName);
15546                // If the currently set package isn't valid, then it's always
15547                // okay to change it.
15548                if (setting != null) {
15549                    if (compareSignatures(callerSignature,
15550                            setting.signatures.mSignatures)
15551                            != PackageManager.SIGNATURE_MATCH) {
15552                        throw new SecurityException(
15553                                "Caller does not have same cert as old installer package "
15554                                + targetPackageSetting.installerPackageName);
15555                    }
15556                }
15557            }
15558
15559            // Okay!
15560            targetPackageSetting.installerPackageName = installerPackageName;
15561            if (installerPackageName != null) {
15562                mSettings.mInstallerPackages.add(installerPackageName);
15563            }
15564            scheduleWriteSettingsLocked();
15565        }
15566    }
15567
15568    @Override
15569    public void setApplicationCategoryHint(String packageName, int categoryHint,
15570            String callerPackageName) {
15571        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15572            throw new SecurityException("Instant applications don't have access to this method");
15573        }
15574        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15575                callerPackageName);
15576        synchronized (mPackages) {
15577            PackageSetting ps = mSettings.mPackages.get(packageName);
15578            if (ps == null) {
15579                throw new IllegalArgumentException("Unknown target package " + packageName);
15580            }
15581            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15582                throw new IllegalArgumentException("Unknown target package " + packageName);
15583            }
15584            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15585                throw new IllegalArgumentException("Calling package " + callerPackageName
15586                        + " is not installer for " + packageName);
15587            }
15588
15589            if (ps.categoryHint != categoryHint) {
15590                ps.categoryHint = categoryHint;
15591                scheduleWriteSettingsLocked();
15592            }
15593        }
15594    }
15595
15596    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15597        // Queue up an async operation since the package installation may take a little while.
15598        mHandler.post(new Runnable() {
15599            public void run() {
15600                mHandler.removeCallbacks(this);
15601                 // Result object to be returned
15602                PackageInstalledInfo res = new PackageInstalledInfo();
15603                res.setReturnCode(currentStatus);
15604                res.uid = -1;
15605                res.pkg = null;
15606                res.removedInfo = null;
15607                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15608                    args.doPreInstall(res.returnCode);
15609                    synchronized (mInstallLock) {
15610                        installPackageTracedLI(args, res);
15611                    }
15612                    args.doPostInstall(res.returnCode, res.uid);
15613                }
15614
15615                // A restore should be performed at this point if (a) the install
15616                // succeeded, (b) the operation is not an update, and (c) the new
15617                // package has not opted out of backup participation.
15618                final boolean update = res.removedInfo != null
15619                        && res.removedInfo.removedPackage != null;
15620                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15621                boolean doRestore = !update
15622                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15623
15624                // Set up the post-install work request bookkeeping.  This will be used
15625                // and cleaned up by the post-install event handling regardless of whether
15626                // there's a restore pass performed.  Token values are >= 1.
15627                int token;
15628                if (mNextInstallToken < 0) mNextInstallToken = 1;
15629                token = mNextInstallToken++;
15630
15631                PostInstallData data = new PostInstallData(args, res);
15632                mRunningInstalls.put(token, data);
15633                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15634
15635                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15636                    // Pass responsibility to the Backup Manager.  It will perform a
15637                    // restore if appropriate, then pass responsibility back to the
15638                    // Package Manager to run the post-install observer callbacks
15639                    // and broadcasts.
15640                    IBackupManager bm = IBackupManager.Stub.asInterface(
15641                            ServiceManager.getService(Context.BACKUP_SERVICE));
15642                    if (bm != null) {
15643                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15644                                + " to BM for possible restore");
15645                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15646                        try {
15647                            // TODO: http://b/22388012
15648                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15649                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15650                            } else {
15651                                doRestore = false;
15652                            }
15653                        } catch (RemoteException e) {
15654                            // can't happen; the backup manager is local
15655                        } catch (Exception e) {
15656                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15657                            doRestore = false;
15658                        }
15659                    } else {
15660                        Slog.e(TAG, "Backup Manager not found!");
15661                        doRestore = false;
15662                    }
15663                }
15664
15665                if (!doRestore) {
15666                    // No restore possible, or the Backup Manager was mysteriously not
15667                    // available -- just fire the post-install work request directly.
15668                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15669
15670                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15671
15672                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15673                    mHandler.sendMessage(msg);
15674                }
15675            }
15676        });
15677    }
15678
15679    /**
15680     * Callback from PackageSettings whenever an app is first transitioned out of the
15681     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15682     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15683     * here whether the app is the target of an ongoing install, and only send the
15684     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15685     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15686     * handling.
15687     */
15688    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15689        // Serialize this with the rest of the install-process message chain.  In the
15690        // restore-at-install case, this Runnable will necessarily run before the
15691        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15692        // are coherent.  In the non-restore case, the app has already completed install
15693        // and been launched through some other means, so it is not in a problematic
15694        // state for observers to see the FIRST_LAUNCH signal.
15695        mHandler.post(new Runnable() {
15696            @Override
15697            public void run() {
15698                for (int i = 0; i < mRunningInstalls.size(); i++) {
15699                    final PostInstallData data = mRunningInstalls.valueAt(i);
15700                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15701                        continue;
15702                    }
15703                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15704                        // right package; but is it for the right user?
15705                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15706                            if (userId == data.res.newUsers[uIndex]) {
15707                                if (DEBUG_BACKUP) {
15708                                    Slog.i(TAG, "Package " + pkgName
15709                                            + " being restored so deferring FIRST_LAUNCH");
15710                                }
15711                                return;
15712                            }
15713                        }
15714                    }
15715                }
15716                // didn't find it, so not being restored
15717                if (DEBUG_BACKUP) {
15718                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15719                }
15720                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15721            }
15722        });
15723    }
15724
15725    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15726        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15727                installerPkg, null, userIds);
15728    }
15729
15730    private abstract class HandlerParams {
15731        private static final int MAX_RETRIES = 4;
15732
15733        /**
15734         * Number of times startCopy() has been attempted and had a non-fatal
15735         * error.
15736         */
15737        private int mRetries = 0;
15738
15739        /** User handle for the user requesting the information or installation. */
15740        private final UserHandle mUser;
15741        String traceMethod;
15742        int traceCookie;
15743
15744        HandlerParams(UserHandle user) {
15745            mUser = user;
15746        }
15747
15748        UserHandle getUser() {
15749            return mUser;
15750        }
15751
15752        HandlerParams setTraceMethod(String traceMethod) {
15753            this.traceMethod = traceMethod;
15754            return this;
15755        }
15756
15757        HandlerParams setTraceCookie(int traceCookie) {
15758            this.traceCookie = traceCookie;
15759            return this;
15760        }
15761
15762        final boolean startCopy() {
15763            boolean res;
15764            try {
15765                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15766
15767                if (++mRetries > MAX_RETRIES) {
15768                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15769                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15770                    handleServiceError();
15771                    return false;
15772                } else {
15773                    handleStartCopy();
15774                    res = true;
15775                }
15776            } catch (RemoteException e) {
15777                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15778                mHandler.sendEmptyMessage(MCS_RECONNECT);
15779                res = false;
15780            }
15781            handleReturnCode();
15782            return res;
15783        }
15784
15785        final void serviceError() {
15786            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15787            handleServiceError();
15788            handleReturnCode();
15789        }
15790
15791        abstract void handleStartCopy() throws RemoteException;
15792        abstract void handleServiceError();
15793        abstract void handleReturnCode();
15794    }
15795
15796    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15797        for (File path : paths) {
15798            try {
15799                mcs.clearDirectory(path.getAbsolutePath());
15800            } catch (RemoteException e) {
15801            }
15802        }
15803    }
15804
15805    static class OriginInfo {
15806        /**
15807         * Location where install is coming from, before it has been
15808         * copied/renamed into place. This could be a single monolithic APK
15809         * file, or a cluster directory. This location may be untrusted.
15810         */
15811        final File file;
15812        final String cid;
15813
15814        /**
15815         * Flag indicating that {@link #file} or {@link #cid} has already been
15816         * staged, meaning downstream users don't need to defensively copy the
15817         * contents.
15818         */
15819        final boolean staged;
15820
15821        /**
15822         * Flag indicating that {@link #file} or {@link #cid} is an already
15823         * installed app that is being moved.
15824         */
15825        final boolean existing;
15826
15827        final String resolvedPath;
15828        final File resolvedFile;
15829
15830        static OriginInfo fromNothing() {
15831            return new OriginInfo(null, null, false, false);
15832        }
15833
15834        static OriginInfo fromUntrustedFile(File file) {
15835            return new OriginInfo(file, null, false, false);
15836        }
15837
15838        static OriginInfo fromExistingFile(File file) {
15839            return new OriginInfo(file, null, false, true);
15840        }
15841
15842        static OriginInfo fromStagedFile(File file) {
15843            return new OriginInfo(file, null, true, false);
15844        }
15845
15846        static OriginInfo fromStagedContainer(String cid) {
15847            return new OriginInfo(null, cid, true, false);
15848        }
15849
15850        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15851            this.file = file;
15852            this.cid = cid;
15853            this.staged = staged;
15854            this.existing = existing;
15855
15856            if (cid != null) {
15857                resolvedPath = PackageHelper.getSdDir(cid);
15858                resolvedFile = new File(resolvedPath);
15859            } else if (file != null) {
15860                resolvedPath = file.getAbsolutePath();
15861                resolvedFile = file;
15862            } else {
15863                resolvedPath = null;
15864                resolvedFile = null;
15865            }
15866        }
15867    }
15868
15869    static class MoveInfo {
15870        final int moveId;
15871        final String fromUuid;
15872        final String toUuid;
15873        final String packageName;
15874        final String dataAppName;
15875        final int appId;
15876        final String seinfo;
15877        final int targetSdkVersion;
15878
15879        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15880                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15881            this.moveId = moveId;
15882            this.fromUuid = fromUuid;
15883            this.toUuid = toUuid;
15884            this.packageName = packageName;
15885            this.dataAppName = dataAppName;
15886            this.appId = appId;
15887            this.seinfo = seinfo;
15888            this.targetSdkVersion = targetSdkVersion;
15889        }
15890    }
15891
15892    static class VerificationInfo {
15893        /** A constant used to indicate that a uid value is not present. */
15894        public static final int NO_UID = -1;
15895
15896        /** URI referencing where the package was downloaded from. */
15897        final Uri originatingUri;
15898
15899        /** HTTP referrer URI associated with the originatingURI. */
15900        final Uri referrer;
15901
15902        /** UID of the application that the install request originated from. */
15903        final int originatingUid;
15904
15905        /** UID of application requesting the install */
15906        final int installerUid;
15907
15908        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15909            this.originatingUri = originatingUri;
15910            this.referrer = referrer;
15911            this.originatingUid = originatingUid;
15912            this.installerUid = installerUid;
15913        }
15914    }
15915
15916    class InstallParams extends HandlerParams {
15917        final OriginInfo origin;
15918        final MoveInfo move;
15919        final IPackageInstallObserver2 observer;
15920        int installFlags;
15921        final String installerPackageName;
15922        final String volumeUuid;
15923        private InstallArgs mArgs;
15924        private int mRet;
15925        final String packageAbiOverride;
15926        final String[] grantedRuntimePermissions;
15927        final VerificationInfo verificationInfo;
15928        final Certificate[][] certificates;
15929        final int installReason;
15930
15931        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15932                int installFlags, String installerPackageName, String volumeUuid,
15933                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15934                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15935            super(user);
15936            this.origin = origin;
15937            this.move = move;
15938            this.observer = observer;
15939            this.installFlags = installFlags;
15940            this.installerPackageName = installerPackageName;
15941            this.volumeUuid = volumeUuid;
15942            this.verificationInfo = verificationInfo;
15943            this.packageAbiOverride = packageAbiOverride;
15944            this.grantedRuntimePermissions = grantedPermissions;
15945            this.certificates = certificates;
15946            this.installReason = installReason;
15947        }
15948
15949        @Override
15950        public String toString() {
15951            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15952                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15953        }
15954
15955        private int installLocationPolicy(PackageInfoLite pkgLite) {
15956            String packageName = pkgLite.packageName;
15957            int installLocation = pkgLite.installLocation;
15958            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15959            // reader
15960            synchronized (mPackages) {
15961                // Currently installed package which the new package is attempting to replace or
15962                // null if no such package is installed.
15963                PackageParser.Package installedPkg = mPackages.get(packageName);
15964                // Package which currently owns the data which the new package will own if installed.
15965                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15966                // will be null whereas dataOwnerPkg will contain information about the package
15967                // which was uninstalled while keeping its data.
15968                PackageParser.Package dataOwnerPkg = installedPkg;
15969                if (dataOwnerPkg  == null) {
15970                    PackageSetting ps = mSettings.mPackages.get(packageName);
15971                    if (ps != null) {
15972                        dataOwnerPkg = ps.pkg;
15973                    }
15974                }
15975
15976                if (dataOwnerPkg != null) {
15977                    // If installed, the package will get access to data left on the device by its
15978                    // predecessor. As a security measure, this is permited only if this is not a
15979                    // version downgrade or if the predecessor package is marked as debuggable and
15980                    // a downgrade is explicitly requested.
15981                    //
15982                    // On debuggable platform builds, downgrades are permitted even for
15983                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15984                    // not offer security guarantees and thus it's OK to disable some security
15985                    // mechanisms to make debugging/testing easier on those builds. However, even on
15986                    // debuggable builds downgrades of packages are permitted only if requested via
15987                    // installFlags. This is because we aim to keep the behavior of debuggable
15988                    // platform builds as close as possible to the behavior of non-debuggable
15989                    // platform builds.
15990                    final boolean downgradeRequested =
15991                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15992                    final boolean packageDebuggable =
15993                                (dataOwnerPkg.applicationInfo.flags
15994                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15995                    final boolean downgradePermitted =
15996                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15997                    if (!downgradePermitted) {
15998                        try {
15999                            checkDowngrade(dataOwnerPkg, pkgLite);
16000                        } catch (PackageManagerException e) {
16001                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16002                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16003                        }
16004                    }
16005                }
16006
16007                if (installedPkg != null) {
16008                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16009                        // Check for updated system application.
16010                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16011                            if (onSd) {
16012                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16013                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16014                            }
16015                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16016                        } else {
16017                            if (onSd) {
16018                                // Install flag overrides everything.
16019                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16020                            }
16021                            // If current upgrade specifies particular preference
16022                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16023                                // Application explicitly specified internal.
16024                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16025                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16026                                // App explictly prefers external. Let policy decide
16027                            } else {
16028                                // Prefer previous location
16029                                if (isExternal(installedPkg)) {
16030                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16031                                }
16032                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16033                            }
16034                        }
16035                    } else {
16036                        // Invalid install. Return error code
16037                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16038                    }
16039                }
16040            }
16041            // All the special cases have been taken care of.
16042            // Return result based on recommended install location.
16043            if (onSd) {
16044                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16045            }
16046            return pkgLite.recommendedInstallLocation;
16047        }
16048
16049        /*
16050         * Invoke remote method to get package information and install
16051         * location values. Override install location based on default
16052         * policy if needed and then create install arguments based
16053         * on the install location.
16054         */
16055        public void handleStartCopy() throws RemoteException {
16056            int ret = PackageManager.INSTALL_SUCCEEDED;
16057
16058            // If we're already staged, we've firmly committed to an install location
16059            if (origin.staged) {
16060                if (origin.file != null) {
16061                    installFlags |= PackageManager.INSTALL_INTERNAL;
16062                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16063                } else if (origin.cid != null) {
16064                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16065                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16066                } else {
16067                    throw new IllegalStateException("Invalid stage location");
16068                }
16069            }
16070
16071            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16072            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16073            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16074            PackageInfoLite pkgLite = null;
16075
16076            if (onInt && onSd) {
16077                // Check if both bits are set.
16078                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16079                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16080            } else if (onSd && ephemeral) {
16081                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16082                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16083            } else {
16084                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16085                        packageAbiOverride);
16086
16087                if (DEBUG_EPHEMERAL && ephemeral) {
16088                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16089                }
16090
16091                /*
16092                 * If we have too little free space, try to free cache
16093                 * before giving up.
16094                 */
16095                if (!origin.staged && pkgLite.recommendedInstallLocation
16096                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16097                    // TODO: focus freeing disk space on the target device
16098                    final StorageManager storage = StorageManager.from(mContext);
16099                    final long lowThreshold = storage.getStorageLowBytes(
16100                            Environment.getDataDirectory());
16101
16102                    final long sizeBytes = mContainerService.calculateInstalledSize(
16103                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16104
16105                    try {
16106                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16107                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16108                                installFlags, packageAbiOverride);
16109                    } catch (InstallerException e) {
16110                        Slog.w(TAG, "Failed to free cache", e);
16111                    }
16112
16113                    /*
16114                     * The cache free must have deleted the file we
16115                     * downloaded to install.
16116                     *
16117                     * TODO: fix the "freeCache" call to not delete
16118                     *       the file we care about.
16119                     */
16120                    if (pkgLite.recommendedInstallLocation
16121                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16122                        pkgLite.recommendedInstallLocation
16123                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16124                    }
16125                }
16126            }
16127
16128            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16129                int loc = pkgLite.recommendedInstallLocation;
16130                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16131                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16132                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16133                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16134                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16135                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16136                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16137                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16138                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16139                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16140                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16141                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16142                } else {
16143                    // Override with defaults if needed.
16144                    loc = installLocationPolicy(pkgLite);
16145                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16146                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16147                    } else if (!onSd && !onInt) {
16148                        // Override install location with flags
16149                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16150                            // Set the flag to install on external media.
16151                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16152                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16153                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16154                            if (DEBUG_EPHEMERAL) {
16155                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16156                            }
16157                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16158                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16159                                    |PackageManager.INSTALL_INTERNAL);
16160                        } else {
16161                            // Make sure the flag for installing on external
16162                            // media is unset
16163                            installFlags |= PackageManager.INSTALL_INTERNAL;
16164                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16165                        }
16166                    }
16167                }
16168            }
16169
16170            final InstallArgs args = createInstallArgs(this);
16171            mArgs = args;
16172
16173            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16174                // TODO: http://b/22976637
16175                // Apps installed for "all" users use the device owner to verify the app
16176                UserHandle verifierUser = getUser();
16177                if (verifierUser == UserHandle.ALL) {
16178                    verifierUser = UserHandle.SYSTEM;
16179                }
16180
16181                /*
16182                 * Determine if we have any installed package verifiers. If we
16183                 * do, then we'll defer to them to verify the packages.
16184                 */
16185                final int requiredUid = mRequiredVerifierPackage == null ? -1
16186                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16187                                verifierUser.getIdentifier());
16188                final int installerUid =
16189                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16190                if (!origin.existing && requiredUid != -1
16191                        && isVerificationEnabled(
16192                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16193                    final Intent verification = new Intent(
16194                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16195                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16196                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16197                            PACKAGE_MIME_TYPE);
16198                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16199
16200                    // Query all live verifiers based on current user state
16201                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16202                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
16203
16204                    if (DEBUG_VERIFY) {
16205                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16206                                + verification.toString() + " with " + pkgLite.verifiers.length
16207                                + " optional verifiers");
16208                    }
16209
16210                    final int verificationId = mPendingVerificationToken++;
16211
16212                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16213
16214                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16215                            installerPackageName);
16216
16217                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16218                            installFlags);
16219
16220                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16221                            pkgLite.packageName);
16222
16223                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16224                            pkgLite.versionCode);
16225
16226                    if (verificationInfo != null) {
16227                        if (verificationInfo.originatingUri != null) {
16228                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16229                                    verificationInfo.originatingUri);
16230                        }
16231                        if (verificationInfo.referrer != null) {
16232                            verification.putExtra(Intent.EXTRA_REFERRER,
16233                                    verificationInfo.referrer);
16234                        }
16235                        if (verificationInfo.originatingUid >= 0) {
16236                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16237                                    verificationInfo.originatingUid);
16238                        }
16239                        if (verificationInfo.installerUid >= 0) {
16240                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16241                                    verificationInfo.installerUid);
16242                        }
16243                    }
16244
16245                    final PackageVerificationState verificationState = new PackageVerificationState(
16246                            requiredUid, args);
16247
16248                    mPendingVerification.append(verificationId, verificationState);
16249
16250                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16251                            receivers, verificationState);
16252
16253                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16254                    final long idleDuration = getVerificationTimeout();
16255
16256                    /*
16257                     * If any sufficient verifiers were listed in the package
16258                     * manifest, attempt to ask them.
16259                     */
16260                    if (sufficientVerifiers != null) {
16261                        final int N = sufficientVerifiers.size();
16262                        if (N == 0) {
16263                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16264                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16265                        } else {
16266                            for (int i = 0; i < N; i++) {
16267                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16268                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16269                                        verifierComponent.getPackageName(), idleDuration,
16270                                        verifierUser.getIdentifier(), false, "package verifier");
16271
16272                                final Intent sufficientIntent = new Intent(verification);
16273                                sufficientIntent.setComponent(verifierComponent);
16274                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16275                            }
16276                        }
16277                    }
16278
16279                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16280                            mRequiredVerifierPackage, receivers);
16281                    if (ret == PackageManager.INSTALL_SUCCEEDED
16282                            && mRequiredVerifierPackage != null) {
16283                        Trace.asyncTraceBegin(
16284                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16285                        /*
16286                         * Send the intent to the required verification agent,
16287                         * but only start the verification timeout after the
16288                         * target BroadcastReceivers have run.
16289                         */
16290                        verification.setComponent(requiredVerifierComponent);
16291                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16292                                mRequiredVerifierPackage, idleDuration,
16293                                verifierUser.getIdentifier(), false, "package verifier");
16294                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16295                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16296                                new BroadcastReceiver() {
16297                                    @Override
16298                                    public void onReceive(Context context, Intent intent) {
16299                                        final Message msg = mHandler
16300                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16301                                        msg.arg1 = verificationId;
16302                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16303                                    }
16304                                }, null, 0, null, null);
16305
16306                        /*
16307                         * We don't want the copy to proceed until verification
16308                         * succeeds, so null out this field.
16309                         */
16310                        mArgs = null;
16311                    }
16312                } else {
16313                    /*
16314                     * No package verification is enabled, so immediately start
16315                     * the remote call to initiate copy using temporary file.
16316                     */
16317                    ret = args.copyApk(mContainerService, true);
16318                }
16319            }
16320
16321            mRet = ret;
16322        }
16323
16324        @Override
16325        void handleReturnCode() {
16326            // If mArgs is null, then MCS couldn't be reached. When it
16327            // reconnects, it will try again to install. At that point, this
16328            // will succeed.
16329            if (mArgs != null) {
16330                processPendingInstall(mArgs, mRet);
16331            }
16332        }
16333
16334        @Override
16335        void handleServiceError() {
16336            mArgs = createInstallArgs(this);
16337            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16338        }
16339
16340        public boolean isForwardLocked() {
16341            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16342        }
16343    }
16344
16345    /**
16346     * Used during creation of InstallArgs
16347     *
16348     * @param installFlags package installation flags
16349     * @return true if should be installed on external storage
16350     */
16351    private static boolean installOnExternalAsec(int installFlags) {
16352        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16353            return false;
16354        }
16355        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16356            return true;
16357        }
16358        return false;
16359    }
16360
16361    /**
16362     * Used during creation of InstallArgs
16363     *
16364     * @param installFlags package installation flags
16365     * @return true if should be installed as forward locked
16366     */
16367    private static boolean installForwardLocked(int installFlags) {
16368        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16369    }
16370
16371    private InstallArgs createInstallArgs(InstallParams params) {
16372        if (params.move != null) {
16373            return new MoveInstallArgs(params);
16374        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16375            return new AsecInstallArgs(params);
16376        } else {
16377            return new FileInstallArgs(params);
16378        }
16379    }
16380
16381    /**
16382     * Create args that describe an existing installed package. Typically used
16383     * when cleaning up old installs, or used as a move source.
16384     */
16385    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16386            String resourcePath, String[] instructionSets) {
16387        final boolean isInAsec;
16388        if (installOnExternalAsec(installFlags)) {
16389            /* Apps on SD card are always in ASEC containers. */
16390            isInAsec = true;
16391        } else if (installForwardLocked(installFlags)
16392                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16393            /*
16394             * Forward-locked apps are only in ASEC containers if they're the
16395             * new style
16396             */
16397            isInAsec = true;
16398        } else {
16399            isInAsec = false;
16400        }
16401
16402        if (isInAsec) {
16403            return new AsecInstallArgs(codePath, instructionSets,
16404                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16405        } else {
16406            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16407        }
16408    }
16409
16410    static abstract class InstallArgs {
16411        /** @see InstallParams#origin */
16412        final OriginInfo origin;
16413        /** @see InstallParams#move */
16414        final MoveInfo move;
16415
16416        final IPackageInstallObserver2 observer;
16417        // Always refers to PackageManager flags only
16418        final int installFlags;
16419        final String installerPackageName;
16420        final String volumeUuid;
16421        final UserHandle user;
16422        final String abiOverride;
16423        final String[] installGrantPermissions;
16424        /** If non-null, drop an async trace when the install completes */
16425        final String traceMethod;
16426        final int traceCookie;
16427        final Certificate[][] certificates;
16428        final int installReason;
16429
16430        // The list of instruction sets supported by this app. This is currently
16431        // only used during the rmdex() phase to clean up resources. We can get rid of this
16432        // if we move dex files under the common app path.
16433        /* nullable */ String[] instructionSets;
16434
16435        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16436                int installFlags, String installerPackageName, String volumeUuid,
16437                UserHandle user, String[] instructionSets,
16438                String abiOverride, String[] installGrantPermissions,
16439                String traceMethod, int traceCookie, Certificate[][] certificates,
16440                int installReason) {
16441            this.origin = origin;
16442            this.move = move;
16443            this.installFlags = installFlags;
16444            this.observer = observer;
16445            this.installerPackageName = installerPackageName;
16446            this.volumeUuid = volumeUuid;
16447            this.user = user;
16448            this.instructionSets = instructionSets;
16449            this.abiOverride = abiOverride;
16450            this.installGrantPermissions = installGrantPermissions;
16451            this.traceMethod = traceMethod;
16452            this.traceCookie = traceCookie;
16453            this.certificates = certificates;
16454            this.installReason = installReason;
16455        }
16456
16457        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16458        abstract int doPreInstall(int status);
16459
16460        /**
16461         * Rename package into final resting place. All paths on the given
16462         * scanned package should be updated to reflect the rename.
16463         */
16464        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16465        abstract int doPostInstall(int status, int uid);
16466
16467        /** @see PackageSettingBase#codePathString */
16468        abstract String getCodePath();
16469        /** @see PackageSettingBase#resourcePathString */
16470        abstract String getResourcePath();
16471
16472        // Need installer lock especially for dex file removal.
16473        abstract void cleanUpResourcesLI();
16474        abstract boolean doPostDeleteLI(boolean delete);
16475
16476        /**
16477         * Called before the source arguments are copied. This is used mostly
16478         * for MoveParams when it needs to read the source file to put it in the
16479         * destination.
16480         */
16481        int doPreCopy() {
16482            return PackageManager.INSTALL_SUCCEEDED;
16483        }
16484
16485        /**
16486         * Called after the source arguments are copied. This is used mostly for
16487         * MoveParams when it needs to read the source file to put it in the
16488         * destination.
16489         */
16490        int doPostCopy(int uid) {
16491            return PackageManager.INSTALL_SUCCEEDED;
16492        }
16493
16494        protected boolean isFwdLocked() {
16495            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16496        }
16497
16498        protected boolean isExternalAsec() {
16499            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16500        }
16501
16502        protected boolean isEphemeral() {
16503            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16504        }
16505
16506        UserHandle getUser() {
16507            return user;
16508        }
16509    }
16510
16511    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16512        if (!allCodePaths.isEmpty()) {
16513            if (instructionSets == null) {
16514                throw new IllegalStateException("instructionSet == null");
16515            }
16516            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16517            for (String codePath : allCodePaths) {
16518                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16519                    try {
16520                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16521                    } catch (InstallerException ignored) {
16522                    }
16523                }
16524            }
16525        }
16526    }
16527
16528    /**
16529     * Logic to handle installation of non-ASEC applications, including copying
16530     * and renaming logic.
16531     */
16532    class FileInstallArgs extends InstallArgs {
16533        private File codeFile;
16534        private File resourceFile;
16535
16536        // Example topology:
16537        // /data/app/com.example/base.apk
16538        // /data/app/com.example/split_foo.apk
16539        // /data/app/com.example/lib/arm/libfoo.so
16540        // /data/app/com.example/lib/arm64/libfoo.so
16541        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16542
16543        /** New install */
16544        FileInstallArgs(InstallParams params) {
16545            super(params.origin, params.move, params.observer, params.installFlags,
16546                    params.installerPackageName, params.volumeUuid,
16547                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16548                    params.grantedRuntimePermissions,
16549                    params.traceMethod, params.traceCookie, params.certificates,
16550                    params.installReason);
16551            if (isFwdLocked()) {
16552                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16553            }
16554        }
16555
16556        /** Existing install */
16557        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16558            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16559                    null, null, null, 0, null /*certificates*/,
16560                    PackageManager.INSTALL_REASON_UNKNOWN);
16561            this.codeFile = (codePath != null) ? new File(codePath) : null;
16562            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16563        }
16564
16565        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16566            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16567            try {
16568                return doCopyApk(imcs, temp);
16569            } finally {
16570                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16571            }
16572        }
16573
16574        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16575            if (origin.staged) {
16576                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16577                codeFile = origin.file;
16578                resourceFile = origin.file;
16579                return PackageManager.INSTALL_SUCCEEDED;
16580            }
16581
16582            try {
16583                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16584                final File tempDir =
16585                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16586                codeFile = tempDir;
16587                resourceFile = tempDir;
16588            } catch (IOException e) {
16589                Slog.w(TAG, "Failed to create copy file: " + e);
16590                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16591            }
16592
16593            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16594                @Override
16595                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16596                    if (!FileUtils.isValidExtFilename(name)) {
16597                        throw new IllegalArgumentException("Invalid filename: " + name);
16598                    }
16599                    try {
16600                        final File file = new File(codeFile, name);
16601                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16602                                O_RDWR | O_CREAT, 0644);
16603                        Os.chmod(file.getAbsolutePath(), 0644);
16604                        return new ParcelFileDescriptor(fd);
16605                    } catch (ErrnoException e) {
16606                        throw new RemoteException("Failed to open: " + e.getMessage());
16607                    }
16608                }
16609            };
16610
16611            int ret = PackageManager.INSTALL_SUCCEEDED;
16612            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16613            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16614                Slog.e(TAG, "Failed to copy package");
16615                return ret;
16616            }
16617
16618            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16619            NativeLibraryHelper.Handle handle = null;
16620            try {
16621                handle = NativeLibraryHelper.Handle.create(codeFile);
16622                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16623                        abiOverride);
16624            } catch (IOException e) {
16625                Slog.e(TAG, "Copying native libraries failed", e);
16626                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16627            } finally {
16628                IoUtils.closeQuietly(handle);
16629            }
16630
16631            return ret;
16632        }
16633
16634        int doPreInstall(int status) {
16635            if (status != PackageManager.INSTALL_SUCCEEDED) {
16636                cleanUp();
16637            }
16638            return status;
16639        }
16640
16641        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16642            if (status != PackageManager.INSTALL_SUCCEEDED) {
16643                cleanUp();
16644                return false;
16645            }
16646
16647            final File targetDir = codeFile.getParentFile();
16648            final File beforeCodeFile = codeFile;
16649            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16650
16651            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16652            try {
16653                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16654            } catch (ErrnoException e) {
16655                Slog.w(TAG, "Failed to rename", e);
16656                return false;
16657            }
16658
16659            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16660                Slog.w(TAG, "Failed to restorecon");
16661                return false;
16662            }
16663
16664            // Reflect the rename internally
16665            codeFile = afterCodeFile;
16666            resourceFile = afterCodeFile;
16667
16668            // Reflect the rename in scanned details
16669            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16670            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16671                    afterCodeFile, pkg.baseCodePath));
16672            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16673                    afterCodeFile, pkg.splitCodePaths));
16674
16675            // Reflect the rename in app info
16676            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16677            pkg.setApplicationInfoCodePath(pkg.codePath);
16678            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16679            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16680            pkg.setApplicationInfoResourcePath(pkg.codePath);
16681            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16682            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16683
16684            return true;
16685        }
16686
16687        int doPostInstall(int status, int uid) {
16688            if (status != PackageManager.INSTALL_SUCCEEDED) {
16689                cleanUp();
16690            }
16691            return status;
16692        }
16693
16694        @Override
16695        String getCodePath() {
16696            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16697        }
16698
16699        @Override
16700        String getResourcePath() {
16701            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16702        }
16703
16704        private boolean cleanUp() {
16705            if (codeFile == null || !codeFile.exists()) {
16706                return false;
16707            }
16708
16709            removeCodePathLI(codeFile);
16710
16711            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16712                resourceFile.delete();
16713            }
16714
16715            return true;
16716        }
16717
16718        void cleanUpResourcesLI() {
16719            // Try enumerating all code paths before deleting
16720            List<String> allCodePaths = Collections.EMPTY_LIST;
16721            if (codeFile != null && codeFile.exists()) {
16722                try {
16723                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16724                    allCodePaths = pkg.getAllCodePaths();
16725                } catch (PackageParserException e) {
16726                    // Ignored; we tried our best
16727                }
16728            }
16729
16730            cleanUp();
16731            removeDexFiles(allCodePaths, instructionSets);
16732        }
16733
16734        boolean doPostDeleteLI(boolean delete) {
16735            // XXX err, shouldn't we respect the delete flag?
16736            cleanUpResourcesLI();
16737            return true;
16738        }
16739    }
16740
16741    private boolean isAsecExternal(String cid) {
16742        final String asecPath = PackageHelper.getSdFilesystem(cid);
16743        return !asecPath.startsWith(mAsecInternalPath);
16744    }
16745
16746    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16747            PackageManagerException {
16748        if (copyRet < 0) {
16749            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16750                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16751                throw new PackageManagerException(copyRet, message);
16752            }
16753        }
16754    }
16755
16756    /**
16757     * Extract the StorageManagerService "container ID" from the full code path of an
16758     * .apk.
16759     */
16760    static String cidFromCodePath(String fullCodePath) {
16761        int eidx = fullCodePath.lastIndexOf("/");
16762        String subStr1 = fullCodePath.substring(0, eidx);
16763        int sidx = subStr1.lastIndexOf("/");
16764        return subStr1.substring(sidx+1, eidx);
16765    }
16766
16767    /**
16768     * Logic to handle installation of ASEC applications, including copying and
16769     * renaming logic.
16770     */
16771    class AsecInstallArgs extends InstallArgs {
16772        static final String RES_FILE_NAME = "pkg.apk";
16773        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16774
16775        String cid;
16776        String packagePath;
16777        String resourcePath;
16778
16779        /** New install */
16780        AsecInstallArgs(InstallParams params) {
16781            super(params.origin, params.move, params.observer, params.installFlags,
16782                    params.installerPackageName, params.volumeUuid,
16783                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16784                    params.grantedRuntimePermissions,
16785                    params.traceMethod, params.traceCookie, params.certificates,
16786                    params.installReason);
16787        }
16788
16789        /** Existing install */
16790        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16791                        boolean isExternal, boolean isForwardLocked) {
16792            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16793                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16794                    instructionSets, null, null, null, 0, null /*certificates*/,
16795                    PackageManager.INSTALL_REASON_UNKNOWN);
16796            // Hackily pretend we're still looking at a full code path
16797            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16798                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16799            }
16800
16801            // Extract cid from fullCodePath
16802            int eidx = fullCodePath.lastIndexOf("/");
16803            String subStr1 = fullCodePath.substring(0, eidx);
16804            int sidx = subStr1.lastIndexOf("/");
16805            cid = subStr1.substring(sidx+1, eidx);
16806            setMountPath(subStr1);
16807        }
16808
16809        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16810            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16811                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16812                    instructionSets, null, null, null, 0, null /*certificates*/,
16813                    PackageManager.INSTALL_REASON_UNKNOWN);
16814            this.cid = cid;
16815            setMountPath(PackageHelper.getSdDir(cid));
16816        }
16817
16818        void createCopyFile() {
16819            cid = mInstallerService.allocateExternalStageCidLegacy();
16820        }
16821
16822        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16823            if (origin.staged && origin.cid != null) {
16824                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16825                cid = origin.cid;
16826                setMountPath(PackageHelper.getSdDir(cid));
16827                return PackageManager.INSTALL_SUCCEEDED;
16828            }
16829
16830            if (temp) {
16831                createCopyFile();
16832            } else {
16833                /*
16834                 * Pre-emptively destroy the container since it's destroyed if
16835                 * copying fails due to it existing anyway.
16836                 */
16837                PackageHelper.destroySdDir(cid);
16838            }
16839
16840            final String newMountPath = imcs.copyPackageToContainer(
16841                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16842                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16843
16844            if (newMountPath != null) {
16845                setMountPath(newMountPath);
16846                return PackageManager.INSTALL_SUCCEEDED;
16847            } else {
16848                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16849            }
16850        }
16851
16852        @Override
16853        String getCodePath() {
16854            return packagePath;
16855        }
16856
16857        @Override
16858        String getResourcePath() {
16859            return resourcePath;
16860        }
16861
16862        int doPreInstall(int status) {
16863            if (status != PackageManager.INSTALL_SUCCEEDED) {
16864                // Destroy container
16865                PackageHelper.destroySdDir(cid);
16866            } else {
16867                boolean mounted = PackageHelper.isContainerMounted(cid);
16868                if (!mounted) {
16869                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16870                            Process.SYSTEM_UID);
16871                    if (newMountPath != null) {
16872                        setMountPath(newMountPath);
16873                    } else {
16874                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16875                    }
16876                }
16877            }
16878            return status;
16879        }
16880
16881        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16882            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16883            String newMountPath = null;
16884            if (PackageHelper.isContainerMounted(cid)) {
16885                // Unmount the container
16886                if (!PackageHelper.unMountSdDir(cid)) {
16887                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16888                    return false;
16889                }
16890            }
16891            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16892                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16893                        " which might be stale. Will try to clean up.");
16894                // Clean up the stale container and proceed to recreate.
16895                if (!PackageHelper.destroySdDir(newCacheId)) {
16896                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16897                    return false;
16898                }
16899                // Successfully cleaned up stale container. Try to rename again.
16900                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16901                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16902                            + " inspite of cleaning it up.");
16903                    return false;
16904                }
16905            }
16906            if (!PackageHelper.isContainerMounted(newCacheId)) {
16907                Slog.w(TAG, "Mounting container " + newCacheId);
16908                newMountPath = PackageHelper.mountSdDir(newCacheId,
16909                        getEncryptKey(), Process.SYSTEM_UID);
16910            } else {
16911                newMountPath = PackageHelper.getSdDir(newCacheId);
16912            }
16913            if (newMountPath == null) {
16914                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16915                return false;
16916            }
16917            Log.i(TAG, "Succesfully renamed " + cid +
16918                    " to " + newCacheId +
16919                    " at new path: " + newMountPath);
16920            cid = newCacheId;
16921
16922            final File beforeCodeFile = new File(packagePath);
16923            setMountPath(newMountPath);
16924            final File afterCodeFile = new File(packagePath);
16925
16926            // Reflect the rename in scanned details
16927            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16928            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16929                    afterCodeFile, pkg.baseCodePath));
16930            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16931                    afterCodeFile, pkg.splitCodePaths));
16932
16933            // Reflect the rename in app info
16934            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16935            pkg.setApplicationInfoCodePath(pkg.codePath);
16936            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16937            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16938            pkg.setApplicationInfoResourcePath(pkg.codePath);
16939            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16940            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16941
16942            return true;
16943        }
16944
16945        private void setMountPath(String mountPath) {
16946            final File mountFile = new File(mountPath);
16947
16948            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16949            if (monolithicFile.exists()) {
16950                packagePath = monolithicFile.getAbsolutePath();
16951                if (isFwdLocked()) {
16952                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16953                } else {
16954                    resourcePath = packagePath;
16955                }
16956            } else {
16957                packagePath = mountFile.getAbsolutePath();
16958                resourcePath = packagePath;
16959            }
16960        }
16961
16962        int doPostInstall(int status, int uid) {
16963            if (status != PackageManager.INSTALL_SUCCEEDED) {
16964                cleanUp();
16965            } else {
16966                final int groupOwner;
16967                final String protectedFile;
16968                if (isFwdLocked()) {
16969                    groupOwner = UserHandle.getSharedAppGid(uid);
16970                    protectedFile = RES_FILE_NAME;
16971                } else {
16972                    groupOwner = -1;
16973                    protectedFile = null;
16974                }
16975
16976                if (uid < Process.FIRST_APPLICATION_UID
16977                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16978                    Slog.e(TAG, "Failed to finalize " + cid);
16979                    PackageHelper.destroySdDir(cid);
16980                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16981                }
16982
16983                boolean mounted = PackageHelper.isContainerMounted(cid);
16984                if (!mounted) {
16985                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16986                }
16987            }
16988            return status;
16989        }
16990
16991        private void cleanUp() {
16992            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16993
16994            // Destroy secure container
16995            PackageHelper.destroySdDir(cid);
16996        }
16997
16998        private List<String> getAllCodePaths() {
16999            final File codeFile = new File(getCodePath());
17000            if (codeFile != null && codeFile.exists()) {
17001                try {
17002                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17003                    return pkg.getAllCodePaths();
17004                } catch (PackageParserException e) {
17005                    // Ignored; we tried our best
17006                }
17007            }
17008            return Collections.EMPTY_LIST;
17009        }
17010
17011        void cleanUpResourcesLI() {
17012            // Enumerate all code paths before deleting
17013            cleanUpResourcesLI(getAllCodePaths());
17014        }
17015
17016        private void cleanUpResourcesLI(List<String> allCodePaths) {
17017            cleanUp();
17018            removeDexFiles(allCodePaths, instructionSets);
17019        }
17020
17021        String getPackageName() {
17022            return getAsecPackageName(cid);
17023        }
17024
17025        boolean doPostDeleteLI(boolean delete) {
17026            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17027            final List<String> allCodePaths = getAllCodePaths();
17028            boolean mounted = PackageHelper.isContainerMounted(cid);
17029            if (mounted) {
17030                // Unmount first
17031                if (PackageHelper.unMountSdDir(cid)) {
17032                    mounted = false;
17033                }
17034            }
17035            if (!mounted && delete) {
17036                cleanUpResourcesLI(allCodePaths);
17037            }
17038            return !mounted;
17039        }
17040
17041        @Override
17042        int doPreCopy() {
17043            if (isFwdLocked()) {
17044                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17045                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17046                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17047                }
17048            }
17049
17050            return PackageManager.INSTALL_SUCCEEDED;
17051        }
17052
17053        @Override
17054        int doPostCopy(int uid) {
17055            if (isFwdLocked()) {
17056                if (uid < Process.FIRST_APPLICATION_UID
17057                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17058                                RES_FILE_NAME)) {
17059                    Slog.e(TAG, "Failed to finalize " + cid);
17060                    PackageHelper.destroySdDir(cid);
17061                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17062                }
17063            }
17064
17065            return PackageManager.INSTALL_SUCCEEDED;
17066        }
17067    }
17068
17069    /**
17070     * Logic to handle movement of existing installed applications.
17071     */
17072    class MoveInstallArgs extends InstallArgs {
17073        private File codeFile;
17074        private File resourceFile;
17075
17076        /** New install */
17077        MoveInstallArgs(InstallParams params) {
17078            super(params.origin, params.move, params.observer, params.installFlags,
17079                    params.installerPackageName, params.volumeUuid,
17080                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17081                    params.grantedRuntimePermissions,
17082                    params.traceMethod, params.traceCookie, params.certificates,
17083                    params.installReason);
17084        }
17085
17086        int copyApk(IMediaContainerService imcs, boolean temp) {
17087            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17088                    + move.fromUuid + " to " + move.toUuid);
17089            synchronized (mInstaller) {
17090                try {
17091                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17092                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17093                } catch (InstallerException e) {
17094                    Slog.w(TAG, "Failed to move app", e);
17095                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17096                }
17097            }
17098
17099            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17100            resourceFile = codeFile;
17101            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17102
17103            return PackageManager.INSTALL_SUCCEEDED;
17104        }
17105
17106        int doPreInstall(int status) {
17107            if (status != PackageManager.INSTALL_SUCCEEDED) {
17108                cleanUp(move.toUuid);
17109            }
17110            return status;
17111        }
17112
17113        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17114            if (status != PackageManager.INSTALL_SUCCEEDED) {
17115                cleanUp(move.toUuid);
17116                return false;
17117            }
17118
17119            // Reflect the move in app info
17120            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17121            pkg.setApplicationInfoCodePath(pkg.codePath);
17122            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17123            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17124            pkg.setApplicationInfoResourcePath(pkg.codePath);
17125            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17126            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17127
17128            return true;
17129        }
17130
17131        int doPostInstall(int status, int uid) {
17132            if (status == PackageManager.INSTALL_SUCCEEDED) {
17133                cleanUp(move.fromUuid);
17134            } else {
17135                cleanUp(move.toUuid);
17136            }
17137            return status;
17138        }
17139
17140        @Override
17141        String getCodePath() {
17142            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17143        }
17144
17145        @Override
17146        String getResourcePath() {
17147            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17148        }
17149
17150        private boolean cleanUp(String volumeUuid) {
17151            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17152                    move.dataAppName);
17153            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17154            final int[] userIds = sUserManager.getUserIds();
17155            synchronized (mInstallLock) {
17156                // Clean up both app data and code
17157                // All package moves are frozen until finished
17158                for (int userId : userIds) {
17159                    try {
17160                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17161                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17162                    } catch (InstallerException e) {
17163                        Slog.w(TAG, String.valueOf(e));
17164                    }
17165                }
17166                removeCodePathLI(codeFile);
17167            }
17168            return true;
17169        }
17170
17171        void cleanUpResourcesLI() {
17172            throw new UnsupportedOperationException();
17173        }
17174
17175        boolean doPostDeleteLI(boolean delete) {
17176            throw new UnsupportedOperationException();
17177        }
17178    }
17179
17180    static String getAsecPackageName(String packageCid) {
17181        int idx = packageCid.lastIndexOf("-");
17182        if (idx == -1) {
17183            return packageCid;
17184        }
17185        return packageCid.substring(0, idx);
17186    }
17187
17188    // Utility method used to create code paths based on package name and available index.
17189    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17190        String idxStr = "";
17191        int idx = 1;
17192        // Fall back to default value of idx=1 if prefix is not
17193        // part of oldCodePath
17194        if (oldCodePath != null) {
17195            String subStr = oldCodePath;
17196            // Drop the suffix right away
17197            if (suffix != null && subStr.endsWith(suffix)) {
17198                subStr = subStr.substring(0, subStr.length() - suffix.length());
17199            }
17200            // If oldCodePath already contains prefix find out the
17201            // ending index to either increment or decrement.
17202            int sidx = subStr.lastIndexOf(prefix);
17203            if (sidx != -1) {
17204                subStr = subStr.substring(sidx + prefix.length());
17205                if (subStr != null) {
17206                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17207                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17208                    }
17209                    try {
17210                        idx = Integer.parseInt(subStr);
17211                        if (idx <= 1) {
17212                            idx++;
17213                        } else {
17214                            idx--;
17215                        }
17216                    } catch(NumberFormatException e) {
17217                    }
17218                }
17219            }
17220        }
17221        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17222        return prefix + idxStr;
17223    }
17224
17225    private File getNextCodePath(File targetDir, String packageName) {
17226        File result;
17227        SecureRandom random = new SecureRandom();
17228        byte[] bytes = new byte[16];
17229        do {
17230            random.nextBytes(bytes);
17231            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17232            result = new File(targetDir, packageName + "-" + suffix);
17233        } while (result.exists());
17234        return result;
17235    }
17236
17237    // Utility method that returns the relative package path with respect
17238    // to the installation directory. Like say for /data/data/com.test-1.apk
17239    // string com.test-1 is returned.
17240    static String deriveCodePathName(String codePath) {
17241        if (codePath == null) {
17242            return null;
17243        }
17244        final File codeFile = new File(codePath);
17245        final String name = codeFile.getName();
17246        if (codeFile.isDirectory()) {
17247            return name;
17248        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17249            final int lastDot = name.lastIndexOf('.');
17250            return name.substring(0, lastDot);
17251        } else {
17252            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17253            return null;
17254        }
17255    }
17256
17257    static class PackageInstalledInfo {
17258        String name;
17259        int uid;
17260        // The set of users that originally had this package installed.
17261        int[] origUsers;
17262        // The set of users that now have this package installed.
17263        int[] newUsers;
17264        PackageParser.Package pkg;
17265        int returnCode;
17266        String returnMsg;
17267        PackageRemovedInfo removedInfo;
17268        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17269
17270        public void setError(int code, String msg) {
17271            setReturnCode(code);
17272            setReturnMessage(msg);
17273            Slog.w(TAG, msg);
17274        }
17275
17276        public void setError(String msg, PackageParserException e) {
17277            setReturnCode(e.error);
17278            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17279            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17280            for (int i = 0; i < childCount; i++) {
17281                addedChildPackages.valueAt(i).setError(msg, e);
17282            }
17283            Slog.w(TAG, msg, e);
17284        }
17285
17286        public void setError(String msg, PackageManagerException e) {
17287            returnCode = e.error;
17288            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17289            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17290            for (int i = 0; i < childCount; i++) {
17291                addedChildPackages.valueAt(i).setError(msg, e);
17292            }
17293            Slog.w(TAG, msg, e);
17294        }
17295
17296        public void setReturnCode(int returnCode) {
17297            this.returnCode = returnCode;
17298            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17299            for (int i = 0; i < childCount; i++) {
17300                addedChildPackages.valueAt(i).returnCode = returnCode;
17301            }
17302        }
17303
17304        private void setReturnMessage(String returnMsg) {
17305            this.returnMsg = returnMsg;
17306            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17307            for (int i = 0; i < childCount; i++) {
17308                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17309            }
17310        }
17311
17312        // In some error cases we want to convey more info back to the observer
17313        String origPackage;
17314        String origPermission;
17315    }
17316
17317    /*
17318     * Install a non-existing package.
17319     */
17320    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17321            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17322            PackageInstalledInfo res, int installReason) {
17323        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17324
17325        // Remember this for later, in case we need to rollback this install
17326        String pkgName = pkg.packageName;
17327
17328        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17329
17330        synchronized(mPackages) {
17331            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17332            if (renamedPackage != null) {
17333                // A package with the same name is already installed, though
17334                // it has been renamed to an older name.  The package we
17335                // are trying to install should be installed as an update to
17336                // the existing one, but that has not been requested, so bail.
17337                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17338                        + " without first uninstalling package running as "
17339                        + renamedPackage);
17340                return;
17341            }
17342            if (mPackages.containsKey(pkgName)) {
17343                // Don't allow installation over an existing package with the same name.
17344                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17345                        + " without first uninstalling.");
17346                return;
17347            }
17348        }
17349
17350        try {
17351            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17352                    System.currentTimeMillis(), user);
17353
17354            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17355
17356            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17357                prepareAppDataAfterInstallLIF(newPackage);
17358
17359            } else {
17360                // Remove package from internal structures, but keep around any
17361                // data that might have already existed
17362                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17363                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17364            }
17365        } catch (PackageManagerException e) {
17366            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17367        }
17368
17369        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17370    }
17371
17372    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17373        // Can't rotate keys during boot or if sharedUser.
17374        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17375                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17376            return false;
17377        }
17378        // app is using upgradeKeySets; make sure all are valid
17379        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17380        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17381        for (int i = 0; i < upgradeKeySets.length; i++) {
17382            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17383                Slog.wtf(TAG, "Package "
17384                         + (oldPs.name != null ? oldPs.name : "<null>")
17385                         + " contains upgrade-key-set reference to unknown key-set: "
17386                         + upgradeKeySets[i]
17387                         + " reverting to signatures check.");
17388                return false;
17389            }
17390        }
17391        return true;
17392    }
17393
17394    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17395        // Upgrade keysets are being used.  Determine if new package has a superset of the
17396        // required keys.
17397        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17398        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17399        for (int i = 0; i < upgradeKeySets.length; i++) {
17400            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17401            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17402                return true;
17403            }
17404        }
17405        return false;
17406    }
17407
17408    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17409        try (DigestInputStream digestStream =
17410                new DigestInputStream(new FileInputStream(file), digest)) {
17411            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17412        }
17413    }
17414
17415    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17416            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17417            int installReason) {
17418        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17419
17420        final PackageParser.Package oldPackage;
17421        final PackageSetting ps;
17422        final String pkgName = pkg.packageName;
17423        final int[] allUsers;
17424        final int[] installedUsers;
17425
17426        synchronized(mPackages) {
17427            oldPackage = mPackages.get(pkgName);
17428            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17429
17430            // don't allow upgrade to target a release SDK from a pre-release SDK
17431            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17432                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17433            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17434                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17435            if (oldTargetsPreRelease
17436                    && !newTargetsPreRelease
17437                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17438                Slog.w(TAG, "Can't install package targeting released sdk");
17439                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17440                return;
17441            }
17442
17443            ps = mSettings.mPackages.get(pkgName);
17444
17445            // verify signatures are valid
17446            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17447                if (!checkUpgradeKeySetLP(ps, pkg)) {
17448                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17449                            "New package not signed by keys specified by upgrade-keysets: "
17450                                    + pkgName);
17451                    return;
17452                }
17453            } else {
17454                // default to original signature matching
17455                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17456                        != PackageManager.SIGNATURE_MATCH) {
17457                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17458                            "New package has a different signature: " + pkgName);
17459                    return;
17460                }
17461            }
17462
17463            // don't allow a system upgrade unless the upgrade hash matches
17464            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17465                byte[] digestBytes = null;
17466                try {
17467                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17468                    updateDigest(digest, new File(pkg.baseCodePath));
17469                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17470                        for (String path : pkg.splitCodePaths) {
17471                            updateDigest(digest, new File(path));
17472                        }
17473                    }
17474                    digestBytes = digest.digest();
17475                } catch (NoSuchAlgorithmException | IOException e) {
17476                    res.setError(INSTALL_FAILED_INVALID_APK,
17477                            "Could not compute hash: " + pkgName);
17478                    return;
17479                }
17480                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17481                    res.setError(INSTALL_FAILED_INVALID_APK,
17482                            "New package fails restrict-update check: " + pkgName);
17483                    return;
17484                }
17485                // retain upgrade restriction
17486                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17487            }
17488
17489            // Check for shared user id changes
17490            String invalidPackageName =
17491                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17492            if (invalidPackageName != null) {
17493                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17494                        "Package " + invalidPackageName + " tried to change user "
17495                                + oldPackage.mSharedUserId);
17496                return;
17497            }
17498
17499            // In case of rollback, remember per-user/profile install state
17500            allUsers = sUserManager.getUserIds();
17501            installedUsers = ps.queryInstalledUsers(allUsers, true);
17502
17503            // don't allow an upgrade from full to ephemeral
17504            if (isInstantApp) {
17505                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17506                    for (int currentUser : allUsers) {
17507                        if (!ps.getInstantApp(currentUser)) {
17508                            // can't downgrade from full to instant
17509                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17510                                    + " for user: " + currentUser);
17511                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17512                            return;
17513                        }
17514                    }
17515                } else if (!ps.getInstantApp(user.getIdentifier())) {
17516                    // can't downgrade from full to instant
17517                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17518                            + " for user: " + user.getIdentifier());
17519                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17520                    return;
17521                }
17522            }
17523        }
17524
17525        // Update what is removed
17526        res.removedInfo = new PackageRemovedInfo(this);
17527        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17528        res.removedInfo.removedPackage = oldPackage.packageName;
17529        res.removedInfo.installerPackageName = ps.installerPackageName;
17530        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17531        res.removedInfo.isUpdate = true;
17532        res.removedInfo.origUsers = installedUsers;
17533        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17534        for (int i = 0; i < installedUsers.length; i++) {
17535            final int userId = installedUsers[i];
17536            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17537        }
17538
17539        final int childCount = (oldPackage.childPackages != null)
17540                ? oldPackage.childPackages.size() : 0;
17541        for (int i = 0; i < childCount; i++) {
17542            boolean childPackageUpdated = false;
17543            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17544            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17545            if (res.addedChildPackages != null) {
17546                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17547                if (childRes != null) {
17548                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17549                    childRes.removedInfo.removedPackage = childPkg.packageName;
17550                    if (childPs != null) {
17551                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17552                    }
17553                    childRes.removedInfo.isUpdate = true;
17554                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17555                    childPackageUpdated = true;
17556                }
17557            }
17558            if (!childPackageUpdated) {
17559                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17560                childRemovedRes.removedPackage = childPkg.packageName;
17561                if (childPs != null) {
17562                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17563                }
17564                childRemovedRes.isUpdate = false;
17565                childRemovedRes.dataRemoved = true;
17566                synchronized (mPackages) {
17567                    if (childPs != null) {
17568                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17569                    }
17570                }
17571                if (res.removedInfo.removedChildPackages == null) {
17572                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17573                }
17574                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17575            }
17576        }
17577
17578        boolean sysPkg = (isSystemApp(oldPackage));
17579        if (sysPkg) {
17580            // Set the system/privileged flags as needed
17581            final boolean privileged =
17582                    (oldPackage.applicationInfo.privateFlags
17583                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17584            final int systemPolicyFlags = policyFlags
17585                    | PackageParser.PARSE_IS_SYSTEM
17586                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17587
17588            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17589                    user, allUsers, installerPackageName, res, installReason);
17590        } else {
17591            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17592                    user, allUsers, installerPackageName, res, installReason);
17593        }
17594    }
17595
17596    @Override
17597    public List<String> getPreviousCodePaths(String packageName) {
17598        final int callingUid = Binder.getCallingUid();
17599        final List<String> result = new ArrayList<>();
17600        if (getInstantAppPackageName(callingUid) != null) {
17601            return result;
17602        }
17603        final PackageSetting ps = mSettings.mPackages.get(packageName);
17604        if (ps != null
17605                && ps.oldCodePaths != null
17606                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17607            result.addAll(ps.oldCodePaths);
17608        }
17609        return result;
17610    }
17611
17612    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17613            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17614            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17615            int installReason) {
17616        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17617                + deletedPackage);
17618
17619        String pkgName = deletedPackage.packageName;
17620        boolean deletedPkg = true;
17621        boolean addedPkg = false;
17622        boolean updatedSettings = false;
17623        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17624        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17625                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17626
17627        final long origUpdateTime = (pkg.mExtras != null)
17628                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17629
17630        // First delete the existing package while retaining the data directory
17631        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17632                res.removedInfo, true, pkg)) {
17633            // If the existing package wasn't successfully deleted
17634            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17635            deletedPkg = false;
17636        } else {
17637            // Successfully deleted the old package; proceed with replace.
17638
17639            // If deleted package lived in a container, give users a chance to
17640            // relinquish resources before killing.
17641            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17642                if (DEBUG_INSTALL) {
17643                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17644                }
17645                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17646                final ArrayList<String> pkgList = new ArrayList<String>(1);
17647                pkgList.add(deletedPackage.applicationInfo.packageName);
17648                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17649            }
17650
17651            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17652                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17653            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17654
17655            try {
17656                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17657                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17658                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17659                        installReason);
17660
17661                // Update the in-memory copy of the previous code paths.
17662                PackageSetting ps = mSettings.mPackages.get(pkgName);
17663                if (!killApp) {
17664                    if (ps.oldCodePaths == null) {
17665                        ps.oldCodePaths = new ArraySet<>();
17666                    }
17667                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17668                    if (deletedPackage.splitCodePaths != null) {
17669                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17670                    }
17671                } else {
17672                    ps.oldCodePaths = null;
17673                }
17674                if (ps.childPackageNames != null) {
17675                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17676                        final String childPkgName = ps.childPackageNames.get(i);
17677                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17678                        childPs.oldCodePaths = ps.oldCodePaths;
17679                    }
17680                }
17681                // set instant app status, but, only if it's explicitly specified
17682                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17683                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17684                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17685                prepareAppDataAfterInstallLIF(newPackage);
17686                addedPkg = true;
17687                mDexManager.notifyPackageUpdated(newPackage.packageName,
17688                        newPackage.baseCodePath, newPackage.splitCodePaths);
17689            } catch (PackageManagerException e) {
17690                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17691            }
17692        }
17693
17694        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17695            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17696
17697            // Revert all internal state mutations and added folders for the failed install
17698            if (addedPkg) {
17699                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17700                        res.removedInfo, true, null);
17701            }
17702
17703            // Restore the old package
17704            if (deletedPkg) {
17705                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17706                File restoreFile = new File(deletedPackage.codePath);
17707                // Parse old package
17708                boolean oldExternal = isExternal(deletedPackage);
17709                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17710                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17711                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17712                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17713                try {
17714                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17715                            null);
17716                } catch (PackageManagerException e) {
17717                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17718                            + e.getMessage());
17719                    return;
17720                }
17721
17722                synchronized (mPackages) {
17723                    // Ensure the installer package name up to date
17724                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17725
17726                    // Update permissions for restored package
17727                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17728
17729                    mSettings.writeLPr();
17730                }
17731
17732                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17733            }
17734        } else {
17735            synchronized (mPackages) {
17736                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17737                if (ps != null) {
17738                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17739                    if (res.removedInfo.removedChildPackages != null) {
17740                        final int childCount = res.removedInfo.removedChildPackages.size();
17741                        // Iterate in reverse as we may modify the collection
17742                        for (int i = childCount - 1; i >= 0; i--) {
17743                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17744                            if (res.addedChildPackages.containsKey(childPackageName)) {
17745                                res.removedInfo.removedChildPackages.removeAt(i);
17746                            } else {
17747                                PackageRemovedInfo childInfo = res.removedInfo
17748                                        .removedChildPackages.valueAt(i);
17749                                childInfo.removedForAllUsers = mPackages.get(
17750                                        childInfo.removedPackage) == null;
17751                            }
17752                        }
17753                    }
17754                }
17755            }
17756        }
17757    }
17758
17759    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17760            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17761            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17762            int installReason) {
17763        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17764                + ", old=" + deletedPackage);
17765
17766        final boolean disabledSystem;
17767
17768        // Remove existing system package
17769        removePackageLI(deletedPackage, true);
17770
17771        synchronized (mPackages) {
17772            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17773        }
17774        if (!disabledSystem) {
17775            // We didn't need to disable the .apk as a current system package,
17776            // which means we are replacing another update that is already
17777            // installed.  We need to make sure to delete the older one's .apk.
17778            res.removedInfo.args = createInstallArgsForExisting(0,
17779                    deletedPackage.applicationInfo.getCodePath(),
17780                    deletedPackage.applicationInfo.getResourcePath(),
17781                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17782        } else {
17783            res.removedInfo.args = null;
17784        }
17785
17786        // Successfully disabled the old package. Now proceed with re-installation
17787        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17788                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17789        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17790
17791        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17792        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17793                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17794
17795        PackageParser.Package newPackage = null;
17796        try {
17797            // Add the package to the internal data structures
17798            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17799
17800            // Set the update and install times
17801            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17802            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17803                    System.currentTimeMillis());
17804
17805            // Update the package dynamic state if succeeded
17806            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17807                // Now that the install succeeded make sure we remove data
17808                // directories for any child package the update removed.
17809                final int deletedChildCount = (deletedPackage.childPackages != null)
17810                        ? deletedPackage.childPackages.size() : 0;
17811                final int newChildCount = (newPackage.childPackages != null)
17812                        ? newPackage.childPackages.size() : 0;
17813                for (int i = 0; i < deletedChildCount; i++) {
17814                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17815                    boolean childPackageDeleted = true;
17816                    for (int j = 0; j < newChildCount; j++) {
17817                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17818                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17819                            childPackageDeleted = false;
17820                            break;
17821                        }
17822                    }
17823                    if (childPackageDeleted) {
17824                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17825                                deletedChildPkg.packageName);
17826                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17827                            PackageRemovedInfo removedChildRes = res.removedInfo
17828                                    .removedChildPackages.get(deletedChildPkg.packageName);
17829                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17830                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17831                        }
17832                    }
17833                }
17834
17835                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17836                        installReason);
17837                prepareAppDataAfterInstallLIF(newPackage);
17838
17839                mDexManager.notifyPackageUpdated(newPackage.packageName,
17840                            newPackage.baseCodePath, newPackage.splitCodePaths);
17841            }
17842        } catch (PackageManagerException e) {
17843            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17844            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17845        }
17846
17847        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17848            // Re installation failed. Restore old information
17849            // Remove new pkg information
17850            if (newPackage != null) {
17851                removeInstalledPackageLI(newPackage, true);
17852            }
17853            // Add back the old system package
17854            try {
17855                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17856            } catch (PackageManagerException e) {
17857                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17858            }
17859
17860            synchronized (mPackages) {
17861                if (disabledSystem) {
17862                    enableSystemPackageLPw(deletedPackage);
17863                }
17864
17865                // Ensure the installer package name up to date
17866                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17867
17868                // Update permissions for restored package
17869                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17870
17871                mSettings.writeLPr();
17872            }
17873
17874            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17875                    + " after failed upgrade");
17876        }
17877    }
17878
17879    /**
17880     * Checks whether the parent or any of the child packages have a change shared
17881     * user. For a package to be a valid update the shred users of the parent and
17882     * the children should match. We may later support changing child shared users.
17883     * @param oldPkg The updated package.
17884     * @param newPkg The update package.
17885     * @return The shared user that change between the versions.
17886     */
17887    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17888            PackageParser.Package newPkg) {
17889        // Check parent shared user
17890        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17891            return newPkg.packageName;
17892        }
17893        // Check child shared users
17894        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17895        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17896        for (int i = 0; i < newChildCount; i++) {
17897            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17898            // If this child was present, did it have the same shared user?
17899            for (int j = 0; j < oldChildCount; j++) {
17900                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17901                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17902                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17903                    return newChildPkg.packageName;
17904                }
17905            }
17906        }
17907        return null;
17908    }
17909
17910    private void removeNativeBinariesLI(PackageSetting ps) {
17911        // Remove the lib path for the parent package
17912        if (ps != null) {
17913            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17914            // Remove the lib path for the child packages
17915            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17916            for (int i = 0; i < childCount; i++) {
17917                PackageSetting childPs = null;
17918                synchronized (mPackages) {
17919                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17920                }
17921                if (childPs != null) {
17922                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17923                            .legacyNativeLibraryPathString);
17924                }
17925            }
17926        }
17927    }
17928
17929    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17930        // Enable the parent package
17931        mSettings.enableSystemPackageLPw(pkg.packageName);
17932        // Enable the child packages
17933        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17934        for (int i = 0; i < childCount; i++) {
17935            PackageParser.Package childPkg = pkg.childPackages.get(i);
17936            mSettings.enableSystemPackageLPw(childPkg.packageName);
17937        }
17938    }
17939
17940    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17941            PackageParser.Package newPkg) {
17942        // Disable the parent package (parent always replaced)
17943        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17944        // Disable the child packages
17945        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17946        for (int i = 0; i < childCount; i++) {
17947            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17948            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17949            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17950        }
17951        return disabled;
17952    }
17953
17954    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17955            String installerPackageName) {
17956        // Enable the parent package
17957        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17958        // Enable the child packages
17959        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17960        for (int i = 0; i < childCount; i++) {
17961            PackageParser.Package childPkg = pkg.childPackages.get(i);
17962            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17963        }
17964    }
17965
17966    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17967        // Collect all used permissions in the UID
17968        ArraySet<String> usedPermissions = new ArraySet<>();
17969        final int packageCount = su.packages.size();
17970        for (int i = 0; i < packageCount; i++) {
17971            PackageSetting ps = su.packages.valueAt(i);
17972            if (ps.pkg == null) {
17973                continue;
17974            }
17975            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17976            for (int j = 0; j < requestedPermCount; j++) {
17977                String permission = ps.pkg.requestedPermissions.get(j);
17978                BasePermission bp = mSettings.mPermissions.get(permission);
17979                if (bp != null) {
17980                    usedPermissions.add(permission);
17981                }
17982            }
17983        }
17984
17985        PermissionsState permissionsState = su.getPermissionsState();
17986        // Prune install permissions
17987        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17988        final int installPermCount = installPermStates.size();
17989        for (int i = installPermCount - 1; i >= 0;  i--) {
17990            PermissionState permissionState = installPermStates.get(i);
17991            if (!usedPermissions.contains(permissionState.getName())) {
17992                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17993                if (bp != null) {
17994                    permissionsState.revokeInstallPermission(bp);
17995                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17996                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17997                }
17998            }
17999        }
18000
18001        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18002
18003        // Prune runtime permissions
18004        for (int userId : allUserIds) {
18005            List<PermissionState> runtimePermStates = permissionsState
18006                    .getRuntimePermissionStates(userId);
18007            final int runtimePermCount = runtimePermStates.size();
18008            for (int i = runtimePermCount - 1; i >= 0; i--) {
18009                PermissionState permissionState = runtimePermStates.get(i);
18010                if (!usedPermissions.contains(permissionState.getName())) {
18011                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18012                    if (bp != null) {
18013                        permissionsState.revokeRuntimePermission(bp, userId);
18014                        permissionsState.updatePermissionFlags(bp, userId,
18015                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18016                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18017                                runtimePermissionChangedUserIds, userId);
18018                    }
18019                }
18020            }
18021        }
18022
18023        return runtimePermissionChangedUserIds;
18024    }
18025
18026    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18027            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18028        // Update the parent package setting
18029        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18030                res, user, installReason);
18031        // Update the child packages setting
18032        final int childCount = (newPackage.childPackages != null)
18033                ? newPackage.childPackages.size() : 0;
18034        for (int i = 0; i < childCount; i++) {
18035            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18036            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18037            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18038                    childRes.origUsers, childRes, user, installReason);
18039        }
18040    }
18041
18042    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18043            String installerPackageName, int[] allUsers, int[] installedForUsers,
18044            PackageInstalledInfo res, UserHandle user, int installReason) {
18045        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18046
18047        String pkgName = newPackage.packageName;
18048        synchronized (mPackages) {
18049            //write settings. the installStatus will be incomplete at this stage.
18050            //note that the new package setting would have already been
18051            //added to mPackages. It hasn't been persisted yet.
18052            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18053            // TODO: Remove this write? It's also written at the end of this method
18054            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18055            mSettings.writeLPr();
18056            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18057        }
18058
18059        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18060        synchronized (mPackages) {
18061            updatePermissionsLPw(newPackage.packageName, newPackage,
18062                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18063                            ? UPDATE_PERMISSIONS_ALL : 0));
18064            // For system-bundled packages, we assume that installing an upgraded version
18065            // of the package implies that the user actually wants to run that new code,
18066            // so we enable the package.
18067            PackageSetting ps = mSettings.mPackages.get(pkgName);
18068            final int userId = user.getIdentifier();
18069            if (ps != null) {
18070                if (isSystemApp(newPackage)) {
18071                    if (DEBUG_INSTALL) {
18072                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18073                    }
18074                    // Enable system package for requested users
18075                    if (res.origUsers != null) {
18076                        for (int origUserId : res.origUsers) {
18077                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18078                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18079                                        origUserId, installerPackageName);
18080                            }
18081                        }
18082                    }
18083                    // Also convey the prior install/uninstall state
18084                    if (allUsers != null && installedForUsers != null) {
18085                        for (int currentUserId : allUsers) {
18086                            final boolean installed = ArrayUtils.contains(
18087                                    installedForUsers, currentUserId);
18088                            if (DEBUG_INSTALL) {
18089                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18090                            }
18091                            ps.setInstalled(installed, currentUserId);
18092                        }
18093                        // these install state changes will be persisted in the
18094                        // upcoming call to mSettings.writeLPr().
18095                    }
18096                }
18097                // It's implied that when a user requests installation, they want the app to be
18098                // installed and enabled.
18099                if (userId != UserHandle.USER_ALL) {
18100                    ps.setInstalled(true, userId);
18101                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18102                }
18103
18104                // When replacing an existing package, preserve the original install reason for all
18105                // users that had the package installed before.
18106                final Set<Integer> previousUserIds = new ArraySet<>();
18107                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18108                    final int installReasonCount = res.removedInfo.installReasons.size();
18109                    for (int i = 0; i < installReasonCount; i++) {
18110                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18111                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18112                        ps.setInstallReason(previousInstallReason, previousUserId);
18113                        previousUserIds.add(previousUserId);
18114                    }
18115                }
18116
18117                // Set install reason for users that are having the package newly installed.
18118                if (userId == UserHandle.USER_ALL) {
18119                    for (int currentUserId : sUserManager.getUserIds()) {
18120                        if (!previousUserIds.contains(currentUserId)) {
18121                            ps.setInstallReason(installReason, currentUserId);
18122                        }
18123                    }
18124                } else if (!previousUserIds.contains(userId)) {
18125                    ps.setInstallReason(installReason, userId);
18126                }
18127                mSettings.writeKernelMappingLPr(ps);
18128            }
18129            res.name = pkgName;
18130            res.uid = newPackage.applicationInfo.uid;
18131            res.pkg = newPackage;
18132            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18133            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18134            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18135            //to update install status
18136            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18137            mSettings.writeLPr();
18138            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18139        }
18140
18141        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18142    }
18143
18144    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18145        try {
18146            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18147            installPackageLI(args, res);
18148        } finally {
18149            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18150        }
18151    }
18152
18153    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18154        final int installFlags = args.installFlags;
18155        final String installerPackageName = args.installerPackageName;
18156        final String volumeUuid = args.volumeUuid;
18157        final File tmpPackageFile = new File(args.getCodePath());
18158        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18159        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18160                || (args.volumeUuid != null));
18161        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18162        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18163        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18164        boolean replace = false;
18165        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18166        if (args.move != null) {
18167            // moving a complete application; perform an initial scan on the new install location
18168            scanFlags |= SCAN_INITIAL;
18169        }
18170        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18171            scanFlags |= SCAN_DONT_KILL_APP;
18172        }
18173        if (instantApp) {
18174            scanFlags |= SCAN_AS_INSTANT_APP;
18175        }
18176        if (fullApp) {
18177            scanFlags |= SCAN_AS_FULL_APP;
18178        }
18179
18180        // Result object to be returned
18181        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18182
18183        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18184
18185        // Sanity check
18186        if (instantApp && (forwardLocked || onExternal)) {
18187            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18188                    + " external=" + onExternal);
18189            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18190            return;
18191        }
18192
18193        // Retrieve PackageSettings and parse package
18194        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18195                | PackageParser.PARSE_ENFORCE_CODE
18196                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18197                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18198                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18199                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18200        PackageParser pp = new PackageParser();
18201        pp.setSeparateProcesses(mSeparateProcesses);
18202        pp.setDisplayMetrics(mMetrics);
18203        pp.setCallback(mPackageParserCallback);
18204
18205        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18206        final PackageParser.Package pkg;
18207        try {
18208            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18209        } catch (PackageParserException e) {
18210            res.setError("Failed parse during installPackageLI", e);
18211            return;
18212        } finally {
18213            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18214        }
18215
18216        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18217        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18218            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18219            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18220                    "Instant app package must target O");
18221            return;
18222        }
18223        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18224            Slog.w(TAG, "Instant app package " + pkg.packageName
18225                    + " does not target targetSandboxVersion 2");
18226            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18227                    "Instant app package must use targetSanboxVersion 2");
18228            return;
18229        }
18230
18231        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18232            // Static shared libraries have synthetic package names
18233            renameStaticSharedLibraryPackage(pkg);
18234
18235            // No static shared libs on external storage
18236            if (onExternal) {
18237                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18238                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18239                        "Packages declaring static-shared libs cannot be updated");
18240                return;
18241            }
18242        }
18243
18244        // If we are installing a clustered package add results for the children
18245        if (pkg.childPackages != null) {
18246            synchronized (mPackages) {
18247                final int childCount = pkg.childPackages.size();
18248                for (int i = 0; i < childCount; i++) {
18249                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18250                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18251                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18252                    childRes.pkg = childPkg;
18253                    childRes.name = childPkg.packageName;
18254                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18255                    if (childPs != null) {
18256                        childRes.origUsers = childPs.queryInstalledUsers(
18257                                sUserManager.getUserIds(), true);
18258                    }
18259                    if ((mPackages.containsKey(childPkg.packageName))) {
18260                        childRes.removedInfo = new PackageRemovedInfo(this);
18261                        childRes.removedInfo.removedPackage = childPkg.packageName;
18262                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18263                    }
18264                    if (res.addedChildPackages == null) {
18265                        res.addedChildPackages = new ArrayMap<>();
18266                    }
18267                    res.addedChildPackages.put(childPkg.packageName, childRes);
18268                }
18269            }
18270        }
18271
18272        // If package doesn't declare API override, mark that we have an install
18273        // time CPU ABI override.
18274        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18275            pkg.cpuAbiOverride = args.abiOverride;
18276        }
18277
18278        String pkgName = res.name = pkg.packageName;
18279        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18280            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18281                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18282                return;
18283            }
18284        }
18285
18286        try {
18287            // either use what we've been given or parse directly from the APK
18288            if (args.certificates != null) {
18289                try {
18290                    PackageParser.populateCertificates(pkg, args.certificates);
18291                } catch (PackageParserException e) {
18292                    // there was something wrong with the certificates we were given;
18293                    // try to pull them from the APK
18294                    PackageParser.collectCertificates(pkg, parseFlags);
18295                }
18296            } else {
18297                PackageParser.collectCertificates(pkg, parseFlags);
18298            }
18299        } catch (PackageParserException e) {
18300            res.setError("Failed collect during installPackageLI", e);
18301            return;
18302        }
18303
18304        // Get rid of all references to package scan path via parser.
18305        pp = null;
18306        String oldCodePath = null;
18307        boolean systemApp = false;
18308        synchronized (mPackages) {
18309            // Check if installing already existing package
18310            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18311                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18312                if (pkg.mOriginalPackages != null
18313                        && pkg.mOriginalPackages.contains(oldName)
18314                        && mPackages.containsKey(oldName)) {
18315                    // This package is derived from an original package,
18316                    // and this device has been updating from that original
18317                    // name.  We must continue using the original name, so
18318                    // rename the new package here.
18319                    pkg.setPackageName(oldName);
18320                    pkgName = pkg.packageName;
18321                    replace = true;
18322                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18323                            + oldName + " pkgName=" + pkgName);
18324                } else if (mPackages.containsKey(pkgName)) {
18325                    // This package, under its official name, already exists
18326                    // on the device; we should replace it.
18327                    replace = true;
18328                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18329                }
18330
18331                // Child packages are installed through the parent package
18332                if (pkg.parentPackage != null) {
18333                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18334                            "Package " + pkg.packageName + " is child of package "
18335                                    + pkg.parentPackage.parentPackage + ". Child packages "
18336                                    + "can be updated only through the parent package.");
18337                    return;
18338                }
18339
18340                if (replace) {
18341                    // Prevent apps opting out from runtime permissions
18342                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18343                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18344                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18345                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18346                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18347                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18348                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18349                                        + " doesn't support runtime permissions but the old"
18350                                        + " target SDK " + oldTargetSdk + " does.");
18351                        return;
18352                    }
18353                    // Prevent apps from downgrading their targetSandbox.
18354                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18355                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18356                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18357                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18358                                "Package " + pkg.packageName + " new target sandbox "
18359                                + newTargetSandbox + " is incompatible with the previous value of"
18360                                + oldTargetSandbox + ".");
18361                        return;
18362                    }
18363
18364                    // Prevent installing of child packages
18365                    if (oldPackage.parentPackage != null) {
18366                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18367                                "Package " + pkg.packageName + " is child of package "
18368                                        + oldPackage.parentPackage + ". Child packages "
18369                                        + "can be updated only through the parent package.");
18370                        return;
18371                    }
18372                }
18373            }
18374
18375            PackageSetting ps = mSettings.mPackages.get(pkgName);
18376            if (ps != null) {
18377                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18378
18379                // Static shared libs have same package with different versions where
18380                // we internally use a synthetic package name to allow multiple versions
18381                // of the same package, therefore we need to compare signatures against
18382                // the package setting for the latest library version.
18383                PackageSetting signatureCheckPs = ps;
18384                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18385                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18386                    if (libraryEntry != null) {
18387                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18388                    }
18389                }
18390
18391                // Quick sanity check that we're signed correctly if updating;
18392                // we'll check this again later when scanning, but we want to
18393                // bail early here before tripping over redefined permissions.
18394                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18395                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18396                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18397                                + pkg.packageName + " upgrade keys do not match the "
18398                                + "previously installed version");
18399                        return;
18400                    }
18401                } else {
18402                    try {
18403                        verifySignaturesLP(signatureCheckPs, pkg);
18404                    } catch (PackageManagerException e) {
18405                        res.setError(e.error, e.getMessage());
18406                        return;
18407                    }
18408                }
18409
18410                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18411                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18412                    systemApp = (ps.pkg.applicationInfo.flags &
18413                            ApplicationInfo.FLAG_SYSTEM) != 0;
18414                }
18415                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18416            }
18417
18418            int N = pkg.permissions.size();
18419            for (int i = N-1; i >= 0; i--) {
18420                PackageParser.Permission perm = pkg.permissions.get(i);
18421                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18422
18423                // Don't allow anyone but the system to define ephemeral permissions.
18424                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18425                        && !systemApp) {
18426                    Slog.w(TAG, "Non-System package " + pkg.packageName
18427                            + " attempting to delcare ephemeral permission "
18428                            + perm.info.name + "; Removing ephemeral.");
18429                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18430                }
18431                // Check whether the newly-scanned package wants to define an already-defined perm
18432                if (bp != null) {
18433                    // If the defining package is signed with our cert, it's okay.  This
18434                    // also includes the "updating the same package" case, of course.
18435                    // "updating same package" could also involve key-rotation.
18436                    final boolean sigsOk;
18437                    if (bp.sourcePackage.equals(pkg.packageName)
18438                            && (bp.packageSetting instanceof PackageSetting)
18439                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18440                                    scanFlags))) {
18441                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18442                    } else {
18443                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18444                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18445                    }
18446                    if (!sigsOk) {
18447                        // If the owning package is the system itself, we log but allow
18448                        // install to proceed; we fail the install on all other permission
18449                        // redefinitions.
18450                        if (!bp.sourcePackage.equals("android")) {
18451                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18452                                    + pkg.packageName + " attempting to redeclare permission "
18453                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18454                            res.origPermission = perm.info.name;
18455                            res.origPackage = bp.sourcePackage;
18456                            return;
18457                        } else {
18458                            Slog.w(TAG, "Package " + pkg.packageName
18459                                    + " attempting to redeclare system permission "
18460                                    + perm.info.name + "; ignoring new declaration");
18461                            pkg.permissions.remove(i);
18462                        }
18463                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18464                        // Prevent apps to change protection level to dangerous from any other
18465                        // type as this would allow a privilege escalation where an app adds a
18466                        // normal/signature permission in other app's group and later redefines
18467                        // it as dangerous leading to the group auto-grant.
18468                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18469                                == PermissionInfo.PROTECTION_DANGEROUS) {
18470                            if (bp != null && !bp.isRuntime()) {
18471                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18472                                        + "non-runtime permission " + perm.info.name
18473                                        + " to runtime; keeping old protection level");
18474                                perm.info.protectionLevel = bp.protectionLevel;
18475                            }
18476                        }
18477                    }
18478                }
18479            }
18480        }
18481
18482        if (systemApp) {
18483            if (onExternal) {
18484                // Abort update; system app can't be replaced with app on sdcard
18485                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18486                        "Cannot install updates to system apps on sdcard");
18487                return;
18488            } else if (instantApp) {
18489                // Abort update; system app can't be replaced with an instant app
18490                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18491                        "Cannot update a system app with an instant app");
18492                return;
18493            }
18494        }
18495
18496        if (args.move != null) {
18497            // We did an in-place move, so dex is ready to roll
18498            scanFlags |= SCAN_NO_DEX;
18499            scanFlags |= SCAN_MOVE;
18500
18501            synchronized (mPackages) {
18502                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18503                if (ps == null) {
18504                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18505                            "Missing settings for moved package " + pkgName);
18506                }
18507
18508                // We moved the entire application as-is, so bring over the
18509                // previously derived ABI information.
18510                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18511                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18512            }
18513
18514        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18515            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18516            scanFlags |= SCAN_NO_DEX;
18517
18518            try {
18519                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18520                    args.abiOverride : pkg.cpuAbiOverride);
18521                final boolean extractNativeLibs = !pkg.isLibrary();
18522                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18523                        extractNativeLibs, mAppLib32InstallDir);
18524            } catch (PackageManagerException pme) {
18525                Slog.e(TAG, "Error deriving application ABI", pme);
18526                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18527                return;
18528            }
18529
18530            // Shared libraries for the package need to be updated.
18531            synchronized (mPackages) {
18532                try {
18533                    updateSharedLibrariesLPr(pkg, null);
18534                } catch (PackageManagerException e) {
18535                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18536                }
18537            }
18538
18539            // dexopt can take some time to complete, so, for instant apps, we skip this
18540            // step during installation. Instead, we'll take extra time the first time the
18541            // instant app starts. It's preferred to do it this way to provide continuous
18542            // progress to the user instead of mysteriously blocking somewhere in the
18543            // middle of running an instant app. The default behaviour can be overridden
18544            // via gservices.
18545            if (!instantApp || Global.getInt(
18546                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18547                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18548                // Do not run PackageDexOptimizer through the local performDexOpt
18549                // method because `pkg` may not be in `mPackages` yet.
18550                //
18551                // Also, don't fail application installs if the dexopt step fails.
18552                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18553                        REASON_INSTALL,
18554                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
18555                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18556                        null /* instructionSets */,
18557                        getOrCreateCompilerPackageStats(pkg),
18558                        mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18559                        dexoptOptions);
18560                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18561            }
18562
18563            // Notify BackgroundDexOptService that the package has been changed.
18564            // If this is an update of a package which used to fail to compile,
18565            // BDOS will remove it from its blacklist.
18566            // TODO: Layering violation
18567            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18568        }
18569
18570        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18571            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18572            return;
18573        }
18574
18575        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18576
18577        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18578                "installPackageLI")) {
18579            if (replace) {
18580                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18581                    // Static libs have a synthetic package name containing the version
18582                    // and cannot be updated as an update would get a new package name,
18583                    // unless this is the exact same version code which is useful for
18584                    // development.
18585                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18586                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18587                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18588                                + "static-shared libs cannot be updated");
18589                        return;
18590                    }
18591                }
18592                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18593                        installerPackageName, res, args.installReason);
18594            } else {
18595                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18596                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18597            }
18598        }
18599
18600        synchronized (mPackages) {
18601            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18602            if (ps != null) {
18603                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18604                ps.setUpdateAvailable(false /*updateAvailable*/);
18605            }
18606
18607            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18608            for (int i = 0; i < childCount; i++) {
18609                PackageParser.Package childPkg = pkg.childPackages.get(i);
18610                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18611                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18612                if (childPs != null) {
18613                    childRes.newUsers = childPs.queryInstalledUsers(
18614                            sUserManager.getUserIds(), true);
18615                }
18616            }
18617
18618            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18619                updateSequenceNumberLP(ps, res.newUsers);
18620                updateInstantAppInstallerLocked(pkgName);
18621            }
18622        }
18623    }
18624
18625    private void startIntentFilterVerifications(int userId, boolean replacing,
18626            PackageParser.Package pkg) {
18627        if (mIntentFilterVerifierComponent == null) {
18628            Slog.w(TAG, "No IntentFilter verification will not be done as "
18629                    + "there is no IntentFilterVerifier available!");
18630            return;
18631        }
18632
18633        final int verifierUid = getPackageUid(
18634                mIntentFilterVerifierComponent.getPackageName(),
18635                MATCH_DEBUG_TRIAGED_MISSING,
18636                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18637
18638        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18639        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18640        mHandler.sendMessage(msg);
18641
18642        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18643        for (int i = 0; i < childCount; i++) {
18644            PackageParser.Package childPkg = pkg.childPackages.get(i);
18645            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18646            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18647            mHandler.sendMessage(msg);
18648        }
18649    }
18650
18651    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18652            PackageParser.Package pkg) {
18653        int size = pkg.activities.size();
18654        if (size == 0) {
18655            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18656                    "No activity, so no need to verify any IntentFilter!");
18657            return;
18658        }
18659
18660        final boolean hasDomainURLs = hasDomainURLs(pkg);
18661        if (!hasDomainURLs) {
18662            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18663                    "No domain URLs, so no need to verify any IntentFilter!");
18664            return;
18665        }
18666
18667        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18668                + " if any IntentFilter from the " + size
18669                + " Activities needs verification ...");
18670
18671        int count = 0;
18672        final String packageName = pkg.packageName;
18673
18674        synchronized (mPackages) {
18675            // If this is a new install and we see that we've already run verification for this
18676            // package, we have nothing to do: it means the state was restored from backup.
18677            if (!replacing) {
18678                IntentFilterVerificationInfo ivi =
18679                        mSettings.getIntentFilterVerificationLPr(packageName);
18680                if (ivi != null) {
18681                    if (DEBUG_DOMAIN_VERIFICATION) {
18682                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18683                                + ivi.getStatusString());
18684                    }
18685                    return;
18686                }
18687            }
18688
18689            // If any filters need to be verified, then all need to be.
18690            boolean needToVerify = false;
18691            for (PackageParser.Activity a : pkg.activities) {
18692                for (ActivityIntentInfo filter : a.intents) {
18693                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18694                        if (DEBUG_DOMAIN_VERIFICATION) {
18695                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18696                        }
18697                        needToVerify = true;
18698                        break;
18699                    }
18700                }
18701            }
18702
18703            if (needToVerify) {
18704                final int verificationId = mIntentFilterVerificationToken++;
18705                for (PackageParser.Activity a : pkg.activities) {
18706                    for (ActivityIntentInfo filter : a.intents) {
18707                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18708                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18709                                    "Verification needed for IntentFilter:" + filter.toString());
18710                            mIntentFilterVerifier.addOneIntentFilterVerification(
18711                                    verifierUid, userId, verificationId, filter, packageName);
18712                            count++;
18713                        }
18714                    }
18715                }
18716            }
18717        }
18718
18719        if (count > 0) {
18720            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18721                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18722                    +  " for userId:" + userId);
18723            mIntentFilterVerifier.startVerifications(userId);
18724        } else {
18725            if (DEBUG_DOMAIN_VERIFICATION) {
18726                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18727            }
18728        }
18729    }
18730
18731    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18732        final ComponentName cn  = filter.activity.getComponentName();
18733        final String packageName = cn.getPackageName();
18734
18735        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18736                packageName);
18737        if (ivi == null) {
18738            return true;
18739        }
18740        int status = ivi.getStatus();
18741        switch (status) {
18742            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18743            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18744                return true;
18745
18746            default:
18747                // Nothing to do
18748                return false;
18749        }
18750    }
18751
18752    private static boolean isMultiArch(ApplicationInfo info) {
18753        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18754    }
18755
18756    private static boolean isExternal(PackageParser.Package pkg) {
18757        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18758    }
18759
18760    private static boolean isExternal(PackageSetting ps) {
18761        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18762    }
18763
18764    private static boolean isSystemApp(PackageParser.Package pkg) {
18765        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18766    }
18767
18768    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18769        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18770    }
18771
18772    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18773        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18774    }
18775
18776    private static boolean isSystemApp(PackageSetting ps) {
18777        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18778    }
18779
18780    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18781        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18782    }
18783
18784    private int packageFlagsToInstallFlags(PackageSetting ps) {
18785        int installFlags = 0;
18786        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18787            // This existing package was an external ASEC install when we have
18788            // the external flag without a UUID
18789            installFlags |= PackageManager.INSTALL_EXTERNAL;
18790        }
18791        if (ps.isForwardLocked()) {
18792            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18793        }
18794        return installFlags;
18795    }
18796
18797    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18798        if (isExternal(pkg)) {
18799            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18800                return StorageManager.UUID_PRIMARY_PHYSICAL;
18801            } else {
18802                return pkg.volumeUuid;
18803            }
18804        } else {
18805            return StorageManager.UUID_PRIVATE_INTERNAL;
18806        }
18807    }
18808
18809    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18810        if (isExternal(pkg)) {
18811            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18812                return mSettings.getExternalVersion();
18813            } else {
18814                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18815            }
18816        } else {
18817            return mSettings.getInternalVersion();
18818        }
18819    }
18820
18821    private void deleteTempPackageFiles() {
18822        final FilenameFilter filter = new FilenameFilter() {
18823            public boolean accept(File dir, String name) {
18824                return name.startsWith("vmdl") && name.endsWith(".tmp");
18825            }
18826        };
18827        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18828            file.delete();
18829        }
18830    }
18831
18832    @Override
18833    public void deletePackageAsUser(String packageName, int versionCode,
18834            IPackageDeleteObserver observer, int userId, int flags) {
18835        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18836                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18837    }
18838
18839    @Override
18840    public void deletePackageVersioned(VersionedPackage versionedPackage,
18841            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18842        final int callingUid = Binder.getCallingUid();
18843        mContext.enforceCallingOrSelfPermission(
18844                android.Manifest.permission.DELETE_PACKAGES, null);
18845        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18846        Preconditions.checkNotNull(versionedPackage);
18847        Preconditions.checkNotNull(observer);
18848        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18849                PackageManager.VERSION_CODE_HIGHEST,
18850                Integer.MAX_VALUE, "versionCode must be >= -1");
18851
18852        final String packageName = versionedPackage.getPackageName();
18853        final int versionCode = versionedPackage.getVersionCode();
18854        final String internalPackageName;
18855        synchronized (mPackages) {
18856            // Normalize package name to handle renamed packages and static libs
18857            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18858                    versionedPackage.getVersionCode());
18859        }
18860
18861        final int uid = Binder.getCallingUid();
18862        if (!isOrphaned(internalPackageName)
18863                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18864            try {
18865                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18866                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18867                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18868                observer.onUserActionRequired(intent);
18869            } catch (RemoteException re) {
18870            }
18871            return;
18872        }
18873        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18874        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18875        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18876            mContext.enforceCallingOrSelfPermission(
18877                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18878                    "deletePackage for user " + userId);
18879        }
18880
18881        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18882            try {
18883                observer.onPackageDeleted(packageName,
18884                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18885            } catch (RemoteException re) {
18886            }
18887            return;
18888        }
18889
18890        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18891            try {
18892                observer.onPackageDeleted(packageName,
18893                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18894            } catch (RemoteException re) {
18895            }
18896            return;
18897        }
18898
18899        if (DEBUG_REMOVE) {
18900            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18901                    + " deleteAllUsers: " + deleteAllUsers + " version="
18902                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18903                    ? "VERSION_CODE_HIGHEST" : versionCode));
18904        }
18905        // Queue up an async operation since the package deletion may take a little while.
18906        mHandler.post(new Runnable() {
18907            public void run() {
18908                mHandler.removeCallbacks(this);
18909                int returnCode;
18910                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18911                boolean doDeletePackage = true;
18912                if (ps != null) {
18913                    final boolean targetIsInstantApp =
18914                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18915                    doDeletePackage = !targetIsInstantApp
18916                            || canViewInstantApps;
18917                }
18918                if (doDeletePackage) {
18919                    if (!deleteAllUsers) {
18920                        returnCode = deletePackageX(internalPackageName, versionCode,
18921                                userId, deleteFlags);
18922                    } else {
18923                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18924                                internalPackageName, users);
18925                        // If nobody is blocking uninstall, proceed with delete for all users
18926                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18927                            returnCode = deletePackageX(internalPackageName, versionCode,
18928                                    userId, deleteFlags);
18929                        } else {
18930                            // Otherwise uninstall individually for users with blockUninstalls=false
18931                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18932                            for (int userId : users) {
18933                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18934                                    returnCode = deletePackageX(internalPackageName, versionCode,
18935                                            userId, userFlags);
18936                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18937                                        Slog.w(TAG, "Package delete failed for user " + userId
18938                                                + ", returnCode " + returnCode);
18939                                    }
18940                                }
18941                            }
18942                            // The app has only been marked uninstalled for certain users.
18943                            // We still need to report that delete was blocked
18944                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18945                        }
18946                    }
18947                } else {
18948                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18949                }
18950                try {
18951                    observer.onPackageDeleted(packageName, returnCode, null);
18952                } catch (RemoteException e) {
18953                    Log.i(TAG, "Observer no longer exists.");
18954                } //end catch
18955            } //end run
18956        });
18957    }
18958
18959    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18960        if (pkg.staticSharedLibName != null) {
18961            return pkg.manifestPackageName;
18962        }
18963        return pkg.packageName;
18964    }
18965
18966    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18967        // Handle renamed packages
18968        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18969        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18970
18971        // Is this a static library?
18972        SparseArray<SharedLibraryEntry> versionedLib =
18973                mStaticLibsByDeclaringPackage.get(packageName);
18974        if (versionedLib == null || versionedLib.size() <= 0) {
18975            return packageName;
18976        }
18977
18978        // Figure out which lib versions the caller can see
18979        SparseIntArray versionsCallerCanSee = null;
18980        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18981        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18982                && callingAppId != Process.ROOT_UID) {
18983            versionsCallerCanSee = new SparseIntArray();
18984            String libName = versionedLib.valueAt(0).info.getName();
18985            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18986            if (uidPackages != null) {
18987                for (String uidPackage : uidPackages) {
18988                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18989                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18990                    if (libIdx >= 0) {
18991                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18992                        versionsCallerCanSee.append(libVersion, libVersion);
18993                    }
18994                }
18995            }
18996        }
18997
18998        // Caller can see nothing - done
18999        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19000            return packageName;
19001        }
19002
19003        // Find the version the caller can see and the app version code
19004        SharedLibraryEntry highestVersion = null;
19005        final int versionCount = versionedLib.size();
19006        for (int i = 0; i < versionCount; i++) {
19007            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19008            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19009                    libEntry.info.getVersion()) < 0) {
19010                continue;
19011            }
19012            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19013            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19014                if (libVersionCode == versionCode) {
19015                    return libEntry.apk;
19016                }
19017            } else if (highestVersion == null) {
19018                highestVersion = libEntry;
19019            } else if (libVersionCode  > highestVersion.info
19020                    .getDeclaringPackage().getVersionCode()) {
19021                highestVersion = libEntry;
19022            }
19023        }
19024
19025        if (highestVersion != null) {
19026            return highestVersion.apk;
19027        }
19028
19029        return packageName;
19030    }
19031
19032    boolean isCallerVerifier(int callingUid) {
19033        final int callingUserId = UserHandle.getUserId(callingUid);
19034        return mRequiredVerifierPackage != null &&
19035                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19036    }
19037
19038    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19039        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19040              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19041            return true;
19042        }
19043        final int callingUserId = UserHandle.getUserId(callingUid);
19044        // If the caller installed the pkgName, then allow it to silently uninstall.
19045        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19046            return true;
19047        }
19048
19049        // Allow package verifier to silently uninstall.
19050        if (mRequiredVerifierPackage != null &&
19051                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19052            return true;
19053        }
19054
19055        // Allow package uninstaller to silently uninstall.
19056        if (mRequiredUninstallerPackage != null &&
19057                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19058            return true;
19059        }
19060
19061        // Allow storage manager to silently uninstall.
19062        if (mStorageManagerPackage != null &&
19063                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19064            return true;
19065        }
19066
19067        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19068        // uninstall for device owner provisioning.
19069        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19070                == PERMISSION_GRANTED) {
19071            return true;
19072        }
19073
19074        return false;
19075    }
19076
19077    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19078        int[] result = EMPTY_INT_ARRAY;
19079        for (int userId : userIds) {
19080            if (getBlockUninstallForUser(packageName, userId)) {
19081                result = ArrayUtils.appendInt(result, userId);
19082            }
19083        }
19084        return result;
19085    }
19086
19087    @Override
19088    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19089        final int callingUid = Binder.getCallingUid();
19090        if (getInstantAppPackageName(callingUid) != null
19091                && !isCallerSameApp(packageName, callingUid)) {
19092            return false;
19093        }
19094        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19095    }
19096
19097    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19098        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19099                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19100        try {
19101            if (dpm != null) {
19102                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19103                        /* callingUserOnly =*/ false);
19104                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19105                        : deviceOwnerComponentName.getPackageName();
19106                // Does the package contains the device owner?
19107                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19108                // this check is probably not needed, since DO should be registered as a device
19109                // admin on some user too. (Original bug for this: b/17657954)
19110                if (packageName.equals(deviceOwnerPackageName)) {
19111                    return true;
19112                }
19113                // Does it contain a device admin for any user?
19114                int[] users;
19115                if (userId == UserHandle.USER_ALL) {
19116                    users = sUserManager.getUserIds();
19117                } else {
19118                    users = new int[]{userId};
19119                }
19120                for (int i = 0; i < users.length; ++i) {
19121                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19122                        return true;
19123                    }
19124                }
19125            }
19126        } catch (RemoteException e) {
19127        }
19128        return false;
19129    }
19130
19131    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19132        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19133    }
19134
19135    /**
19136     *  This method is an internal method that could be get invoked either
19137     *  to delete an installed package or to clean up a failed installation.
19138     *  After deleting an installed package, a broadcast is sent to notify any
19139     *  listeners that the package has been removed. For cleaning up a failed
19140     *  installation, the broadcast is not necessary since the package's
19141     *  installation wouldn't have sent the initial broadcast either
19142     *  The key steps in deleting a package are
19143     *  deleting the package information in internal structures like mPackages,
19144     *  deleting the packages base directories through installd
19145     *  updating mSettings to reflect current status
19146     *  persisting settings for later use
19147     *  sending a broadcast if necessary
19148     */
19149    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19150        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19151        final boolean res;
19152
19153        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19154                ? UserHandle.USER_ALL : userId;
19155
19156        if (isPackageDeviceAdmin(packageName, removeUser)) {
19157            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19158            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19159        }
19160
19161        PackageSetting uninstalledPs = null;
19162        PackageParser.Package pkg = null;
19163
19164        // for the uninstall-updates case and restricted profiles, remember the per-
19165        // user handle installed state
19166        int[] allUsers;
19167        synchronized (mPackages) {
19168            uninstalledPs = mSettings.mPackages.get(packageName);
19169            if (uninstalledPs == null) {
19170                Slog.w(TAG, "Not removing non-existent package " + packageName);
19171                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19172            }
19173
19174            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19175                    && uninstalledPs.versionCode != versionCode) {
19176                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19177                        + uninstalledPs.versionCode + " != " + versionCode);
19178                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19179            }
19180
19181            // Static shared libs can be declared by any package, so let us not
19182            // allow removing a package if it provides a lib others depend on.
19183            pkg = mPackages.get(packageName);
19184
19185            allUsers = sUserManager.getUserIds();
19186
19187            if (pkg != null && pkg.staticSharedLibName != null) {
19188                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19189                        pkg.staticSharedLibVersion);
19190                if (libEntry != null) {
19191                    for (int currUserId : allUsers) {
19192                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19193                            continue;
19194                        }
19195                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19196                                libEntry.info, 0, currUserId);
19197                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19198                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19199                                    + " hosting lib " + libEntry.info.getName() + " version "
19200                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19201                                    + " for user " + currUserId);
19202                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19203                        }
19204                    }
19205                }
19206            }
19207
19208            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19209        }
19210
19211        final int freezeUser;
19212        if (isUpdatedSystemApp(uninstalledPs)
19213                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19214            // We're downgrading a system app, which will apply to all users, so
19215            // freeze them all during the downgrade
19216            freezeUser = UserHandle.USER_ALL;
19217        } else {
19218            freezeUser = removeUser;
19219        }
19220
19221        synchronized (mInstallLock) {
19222            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19223            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19224                    deleteFlags, "deletePackageX")) {
19225                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19226                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19227            }
19228            synchronized (mPackages) {
19229                if (res) {
19230                    if (pkg != null) {
19231                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19232                    }
19233                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19234                    updateInstantAppInstallerLocked(packageName);
19235                }
19236            }
19237        }
19238
19239        if (res) {
19240            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19241            info.sendPackageRemovedBroadcasts(killApp);
19242            info.sendSystemPackageUpdatedBroadcasts();
19243            info.sendSystemPackageAppearedBroadcasts();
19244        }
19245        // Force a gc here.
19246        Runtime.getRuntime().gc();
19247        // Delete the resources here after sending the broadcast to let
19248        // other processes clean up before deleting resources.
19249        if (info.args != null) {
19250            synchronized (mInstallLock) {
19251                info.args.doPostDeleteLI(true);
19252            }
19253        }
19254
19255        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19256    }
19257
19258    static class PackageRemovedInfo {
19259        final PackageSender packageSender;
19260        String removedPackage;
19261        String installerPackageName;
19262        int uid = -1;
19263        int removedAppId = -1;
19264        int[] origUsers;
19265        int[] removedUsers = null;
19266        int[] broadcastUsers = null;
19267        SparseArray<Integer> installReasons;
19268        boolean isRemovedPackageSystemUpdate = false;
19269        boolean isUpdate;
19270        boolean dataRemoved;
19271        boolean removedForAllUsers;
19272        boolean isStaticSharedLib;
19273        // Clean up resources deleted packages.
19274        InstallArgs args = null;
19275        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19276        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19277
19278        PackageRemovedInfo(PackageSender packageSender) {
19279            this.packageSender = packageSender;
19280        }
19281
19282        void sendPackageRemovedBroadcasts(boolean killApp) {
19283            sendPackageRemovedBroadcastInternal(killApp);
19284            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19285            for (int i = 0; i < childCount; i++) {
19286                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19287                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19288            }
19289        }
19290
19291        void sendSystemPackageUpdatedBroadcasts() {
19292            if (isRemovedPackageSystemUpdate) {
19293                sendSystemPackageUpdatedBroadcastsInternal();
19294                final int childCount = (removedChildPackages != null)
19295                        ? removedChildPackages.size() : 0;
19296                for (int i = 0; i < childCount; i++) {
19297                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19298                    if (childInfo.isRemovedPackageSystemUpdate) {
19299                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19300                    }
19301                }
19302            }
19303        }
19304
19305        void sendSystemPackageAppearedBroadcasts() {
19306            final int packageCount = (appearedChildPackages != null)
19307                    ? appearedChildPackages.size() : 0;
19308            for (int i = 0; i < packageCount; i++) {
19309                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19310                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19311                    true /*sendBootCompleted*/, false /*startReceiver*/,
19312                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19313            }
19314        }
19315
19316        private void sendSystemPackageUpdatedBroadcastsInternal() {
19317            Bundle extras = new Bundle(2);
19318            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19319            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19320            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19321                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19322            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19323                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19324            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19325                null, null, 0, removedPackage, null, null);
19326            if (installerPackageName != null) {
19327                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19328                        removedPackage, extras, 0 /*flags*/,
19329                        installerPackageName, null, null);
19330                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19331                        removedPackage, extras, 0 /*flags*/,
19332                        installerPackageName, null, null);
19333            }
19334        }
19335
19336        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19337            // Don't send static shared library removal broadcasts as these
19338            // libs are visible only the the apps that depend on them an one
19339            // cannot remove the library if it has a dependency.
19340            if (isStaticSharedLib) {
19341                return;
19342            }
19343            Bundle extras = new Bundle(2);
19344            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19345            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19346            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19347            if (isUpdate || isRemovedPackageSystemUpdate) {
19348                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19349            }
19350            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19351            if (removedPackage != null) {
19352                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19353                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19354                if (installerPackageName != null) {
19355                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19356                            removedPackage, extras, 0 /*flags*/,
19357                            installerPackageName, null, broadcastUsers);
19358                }
19359                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19360                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19361                        removedPackage, extras,
19362                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19363                        null, null, broadcastUsers);
19364                }
19365            }
19366            if (removedAppId >= 0) {
19367                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19368                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19369                    null, null, broadcastUsers);
19370            }
19371        }
19372
19373        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19374            removedUsers = userIds;
19375            if (removedUsers == null) {
19376                broadcastUsers = null;
19377                return;
19378            }
19379
19380            broadcastUsers = EMPTY_INT_ARRAY;
19381            for (int i = userIds.length - 1; i >= 0; --i) {
19382                final int userId = userIds[i];
19383                if (deletedPackageSetting.getInstantApp(userId)) {
19384                    continue;
19385                }
19386                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19387            }
19388        }
19389    }
19390
19391    /*
19392     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19393     * flag is not set, the data directory is removed as well.
19394     * make sure this flag is set for partially installed apps. If not its meaningless to
19395     * delete a partially installed application.
19396     */
19397    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19398            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19399        String packageName = ps.name;
19400        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19401        // Retrieve object to delete permissions for shared user later on
19402        final PackageParser.Package deletedPkg;
19403        final PackageSetting deletedPs;
19404        // reader
19405        synchronized (mPackages) {
19406            deletedPkg = mPackages.get(packageName);
19407            deletedPs = mSettings.mPackages.get(packageName);
19408            if (outInfo != null) {
19409                outInfo.removedPackage = packageName;
19410                outInfo.installerPackageName = ps.installerPackageName;
19411                outInfo.isStaticSharedLib = deletedPkg != null
19412                        && deletedPkg.staticSharedLibName != null;
19413                outInfo.populateUsers(deletedPs == null ? null
19414                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19415            }
19416        }
19417
19418        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19419
19420        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19421            final PackageParser.Package resolvedPkg;
19422            if (deletedPkg != null) {
19423                resolvedPkg = deletedPkg;
19424            } else {
19425                // We don't have a parsed package when it lives on an ejected
19426                // adopted storage device, so fake something together
19427                resolvedPkg = new PackageParser.Package(ps.name);
19428                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19429            }
19430            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19431                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19432            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19433            if (outInfo != null) {
19434                outInfo.dataRemoved = true;
19435            }
19436            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19437        }
19438
19439        int removedAppId = -1;
19440
19441        // writer
19442        synchronized (mPackages) {
19443            boolean installedStateChanged = false;
19444            if (deletedPs != null) {
19445                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19446                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19447                    clearDefaultBrowserIfNeeded(packageName);
19448                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19449                    removedAppId = mSettings.removePackageLPw(packageName);
19450                    if (outInfo != null) {
19451                        outInfo.removedAppId = removedAppId;
19452                    }
19453                    updatePermissionsLPw(deletedPs.name, null, 0);
19454                    if (deletedPs.sharedUser != null) {
19455                        // Remove permissions associated with package. Since runtime
19456                        // permissions are per user we have to kill the removed package
19457                        // or packages running under the shared user of the removed
19458                        // package if revoking the permissions requested only by the removed
19459                        // package is successful and this causes a change in gids.
19460                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19461                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19462                                    userId);
19463                            if (userIdToKill == UserHandle.USER_ALL
19464                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19465                                // If gids changed for this user, kill all affected packages.
19466                                mHandler.post(new Runnable() {
19467                                    @Override
19468                                    public void run() {
19469                                        // This has to happen with no lock held.
19470                                        killApplication(deletedPs.name, deletedPs.appId,
19471                                                KILL_APP_REASON_GIDS_CHANGED);
19472                                    }
19473                                });
19474                                break;
19475                            }
19476                        }
19477                    }
19478                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19479                }
19480                // make sure to preserve per-user disabled state if this removal was just
19481                // a downgrade of a system app to the factory package
19482                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19483                    if (DEBUG_REMOVE) {
19484                        Slog.d(TAG, "Propagating install state across downgrade");
19485                    }
19486                    for (int userId : allUserHandles) {
19487                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19488                        if (DEBUG_REMOVE) {
19489                            Slog.d(TAG, "    user " + userId + " => " + installed);
19490                        }
19491                        if (installed != ps.getInstalled(userId)) {
19492                            installedStateChanged = true;
19493                        }
19494                        ps.setInstalled(installed, userId);
19495                    }
19496                }
19497            }
19498            // can downgrade to reader
19499            if (writeSettings) {
19500                // Save settings now
19501                mSettings.writeLPr();
19502            }
19503            if (installedStateChanged) {
19504                mSettings.writeKernelMappingLPr(ps);
19505            }
19506        }
19507        if (removedAppId != -1) {
19508            // A user ID was deleted here. Go through all users and remove it
19509            // from KeyStore.
19510            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19511        }
19512    }
19513
19514    static boolean locationIsPrivileged(File path) {
19515        try {
19516            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19517                    .getCanonicalPath();
19518            return path.getCanonicalPath().startsWith(privilegedAppDir);
19519        } catch (IOException e) {
19520            Slog.e(TAG, "Unable to access code path " + path);
19521        }
19522        return false;
19523    }
19524
19525    /*
19526     * Tries to delete system package.
19527     */
19528    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19529            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19530            boolean writeSettings) {
19531        if (deletedPs.parentPackageName != null) {
19532            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19533            return false;
19534        }
19535
19536        final boolean applyUserRestrictions
19537                = (allUserHandles != null) && (outInfo.origUsers != null);
19538        final PackageSetting disabledPs;
19539        // Confirm if the system package has been updated
19540        // An updated system app can be deleted. This will also have to restore
19541        // the system pkg from system partition
19542        // reader
19543        synchronized (mPackages) {
19544            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19545        }
19546
19547        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19548                + " disabledPs=" + disabledPs);
19549
19550        if (disabledPs == null) {
19551            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19552            return false;
19553        } else if (DEBUG_REMOVE) {
19554            Slog.d(TAG, "Deleting system pkg from data partition");
19555        }
19556
19557        if (DEBUG_REMOVE) {
19558            if (applyUserRestrictions) {
19559                Slog.d(TAG, "Remembering install states:");
19560                for (int userId : allUserHandles) {
19561                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19562                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19563                }
19564            }
19565        }
19566
19567        // Delete the updated package
19568        outInfo.isRemovedPackageSystemUpdate = true;
19569        if (outInfo.removedChildPackages != null) {
19570            final int childCount = (deletedPs.childPackageNames != null)
19571                    ? deletedPs.childPackageNames.size() : 0;
19572            for (int i = 0; i < childCount; i++) {
19573                String childPackageName = deletedPs.childPackageNames.get(i);
19574                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19575                        .contains(childPackageName)) {
19576                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19577                            childPackageName);
19578                    if (childInfo != null) {
19579                        childInfo.isRemovedPackageSystemUpdate = true;
19580                    }
19581                }
19582            }
19583        }
19584
19585        if (disabledPs.versionCode < deletedPs.versionCode) {
19586            // Delete data for downgrades
19587            flags &= ~PackageManager.DELETE_KEEP_DATA;
19588        } else {
19589            // Preserve data by setting flag
19590            flags |= PackageManager.DELETE_KEEP_DATA;
19591        }
19592
19593        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19594                outInfo, writeSettings, disabledPs.pkg);
19595        if (!ret) {
19596            return false;
19597        }
19598
19599        // writer
19600        synchronized (mPackages) {
19601            // Reinstate the old system package
19602            enableSystemPackageLPw(disabledPs.pkg);
19603            // Remove any native libraries from the upgraded package.
19604            removeNativeBinariesLI(deletedPs);
19605        }
19606
19607        // Install the system package
19608        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19609        int parseFlags = mDefParseFlags
19610                | PackageParser.PARSE_MUST_BE_APK
19611                | PackageParser.PARSE_IS_SYSTEM
19612                | PackageParser.PARSE_IS_SYSTEM_DIR;
19613        if (locationIsPrivileged(disabledPs.codePath)) {
19614            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19615        }
19616
19617        final PackageParser.Package newPkg;
19618        try {
19619            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19620                0 /* currentTime */, null);
19621        } catch (PackageManagerException e) {
19622            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19623                    + e.getMessage());
19624            return false;
19625        }
19626
19627        try {
19628            // update shared libraries for the newly re-installed system package
19629            updateSharedLibrariesLPr(newPkg, null);
19630        } catch (PackageManagerException e) {
19631            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19632        }
19633
19634        prepareAppDataAfterInstallLIF(newPkg);
19635
19636        // writer
19637        synchronized (mPackages) {
19638            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19639
19640            // Propagate the permissions state as we do not want to drop on the floor
19641            // runtime permissions. The update permissions method below will take
19642            // care of removing obsolete permissions and grant install permissions.
19643            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19644            updatePermissionsLPw(newPkg.packageName, newPkg,
19645                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19646
19647            if (applyUserRestrictions) {
19648                boolean installedStateChanged = false;
19649                if (DEBUG_REMOVE) {
19650                    Slog.d(TAG, "Propagating install state across reinstall");
19651                }
19652                for (int userId : allUserHandles) {
19653                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19654                    if (DEBUG_REMOVE) {
19655                        Slog.d(TAG, "    user " + userId + " => " + installed);
19656                    }
19657                    if (installed != ps.getInstalled(userId)) {
19658                        installedStateChanged = true;
19659                    }
19660                    ps.setInstalled(installed, userId);
19661
19662                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19663                }
19664                // Regardless of writeSettings we need to ensure that this restriction
19665                // state propagation is persisted
19666                mSettings.writeAllUsersPackageRestrictionsLPr();
19667                if (installedStateChanged) {
19668                    mSettings.writeKernelMappingLPr(ps);
19669                }
19670            }
19671            // can downgrade to reader here
19672            if (writeSettings) {
19673                mSettings.writeLPr();
19674            }
19675        }
19676        return true;
19677    }
19678
19679    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19680            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19681            PackageRemovedInfo outInfo, boolean writeSettings,
19682            PackageParser.Package replacingPackage) {
19683        synchronized (mPackages) {
19684            if (outInfo != null) {
19685                outInfo.uid = ps.appId;
19686            }
19687
19688            if (outInfo != null && outInfo.removedChildPackages != null) {
19689                final int childCount = (ps.childPackageNames != null)
19690                        ? ps.childPackageNames.size() : 0;
19691                for (int i = 0; i < childCount; i++) {
19692                    String childPackageName = ps.childPackageNames.get(i);
19693                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19694                    if (childPs == null) {
19695                        return false;
19696                    }
19697                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19698                            childPackageName);
19699                    if (childInfo != null) {
19700                        childInfo.uid = childPs.appId;
19701                    }
19702                }
19703            }
19704        }
19705
19706        // Delete package data from internal structures and also remove data if flag is set
19707        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19708
19709        // Delete the child packages data
19710        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19711        for (int i = 0; i < childCount; i++) {
19712            PackageSetting childPs;
19713            synchronized (mPackages) {
19714                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19715            }
19716            if (childPs != null) {
19717                PackageRemovedInfo childOutInfo = (outInfo != null
19718                        && outInfo.removedChildPackages != null)
19719                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19720                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19721                        && (replacingPackage != null
19722                        && !replacingPackage.hasChildPackage(childPs.name))
19723                        ? flags & ~DELETE_KEEP_DATA : flags;
19724                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19725                        deleteFlags, writeSettings);
19726            }
19727        }
19728
19729        // Delete application code and resources only for parent packages
19730        if (ps.parentPackageName == null) {
19731            if (deleteCodeAndResources && (outInfo != null)) {
19732                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19733                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19734                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19735            }
19736        }
19737
19738        return true;
19739    }
19740
19741    @Override
19742    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19743            int userId) {
19744        mContext.enforceCallingOrSelfPermission(
19745                android.Manifest.permission.DELETE_PACKAGES, null);
19746        synchronized (mPackages) {
19747            // Cannot block uninstall of static shared libs as they are
19748            // considered a part of the using app (emulating static linking).
19749            // Also static libs are installed always on internal storage.
19750            PackageParser.Package pkg = mPackages.get(packageName);
19751            if (pkg != null && pkg.staticSharedLibName != null) {
19752                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19753                        + " providing static shared library: " + pkg.staticSharedLibName);
19754                return false;
19755            }
19756            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19757            mSettings.writePackageRestrictionsLPr(userId);
19758        }
19759        return true;
19760    }
19761
19762    @Override
19763    public boolean getBlockUninstallForUser(String packageName, int userId) {
19764        synchronized (mPackages) {
19765            final PackageSetting ps = mSettings.mPackages.get(packageName);
19766            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19767                return false;
19768            }
19769            return mSettings.getBlockUninstallLPr(userId, packageName);
19770        }
19771    }
19772
19773    @Override
19774    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19775        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19776        synchronized (mPackages) {
19777            PackageSetting ps = mSettings.mPackages.get(packageName);
19778            if (ps == null) {
19779                Log.w(TAG, "Package doesn't exist: " + packageName);
19780                return false;
19781            }
19782            if (systemUserApp) {
19783                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19784            } else {
19785                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19786            }
19787            mSettings.writeLPr();
19788        }
19789        return true;
19790    }
19791
19792    /*
19793     * This method handles package deletion in general
19794     */
19795    private boolean deletePackageLIF(String packageName, UserHandle user,
19796            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19797            PackageRemovedInfo outInfo, boolean writeSettings,
19798            PackageParser.Package replacingPackage) {
19799        if (packageName == null) {
19800            Slog.w(TAG, "Attempt to delete null packageName.");
19801            return false;
19802        }
19803
19804        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19805
19806        PackageSetting ps;
19807        synchronized (mPackages) {
19808            ps = mSettings.mPackages.get(packageName);
19809            if (ps == null) {
19810                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19811                return false;
19812            }
19813
19814            if (ps.parentPackageName != null && (!isSystemApp(ps)
19815                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19816                if (DEBUG_REMOVE) {
19817                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19818                            + ((user == null) ? UserHandle.USER_ALL : user));
19819                }
19820                final int removedUserId = (user != null) ? user.getIdentifier()
19821                        : UserHandle.USER_ALL;
19822                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19823                    return false;
19824                }
19825                markPackageUninstalledForUserLPw(ps, user);
19826                scheduleWritePackageRestrictionsLocked(user);
19827                return true;
19828            }
19829        }
19830
19831        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19832                && user.getIdentifier() != UserHandle.USER_ALL)) {
19833            // The caller is asking that the package only be deleted for a single
19834            // user.  To do this, we just mark its uninstalled state and delete
19835            // its data. If this is a system app, we only allow this to happen if
19836            // they have set the special DELETE_SYSTEM_APP which requests different
19837            // semantics than normal for uninstalling system apps.
19838            markPackageUninstalledForUserLPw(ps, user);
19839
19840            if (!isSystemApp(ps)) {
19841                // Do not uninstall the APK if an app should be cached
19842                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19843                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19844                    // Other user still have this package installed, so all
19845                    // we need to do is clear this user's data and save that
19846                    // it is uninstalled.
19847                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19848                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19849                        return false;
19850                    }
19851                    scheduleWritePackageRestrictionsLocked(user);
19852                    return true;
19853                } else {
19854                    // We need to set it back to 'installed' so the uninstall
19855                    // broadcasts will be sent correctly.
19856                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19857                    ps.setInstalled(true, user.getIdentifier());
19858                    mSettings.writeKernelMappingLPr(ps);
19859                }
19860            } else {
19861                // This is a system app, so we assume that the
19862                // other users still have this package installed, so all
19863                // we need to do is clear this user's data and save that
19864                // it is uninstalled.
19865                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19866                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19867                    return false;
19868                }
19869                scheduleWritePackageRestrictionsLocked(user);
19870                return true;
19871            }
19872        }
19873
19874        // If we are deleting a composite package for all users, keep track
19875        // of result for each child.
19876        if (ps.childPackageNames != null && outInfo != null) {
19877            synchronized (mPackages) {
19878                final int childCount = ps.childPackageNames.size();
19879                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19880                for (int i = 0; i < childCount; i++) {
19881                    String childPackageName = ps.childPackageNames.get(i);
19882                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19883                    childInfo.removedPackage = childPackageName;
19884                    childInfo.installerPackageName = ps.installerPackageName;
19885                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19886                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19887                    if (childPs != null) {
19888                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19889                    }
19890                }
19891            }
19892        }
19893
19894        boolean ret = false;
19895        if (isSystemApp(ps)) {
19896            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19897            // When an updated system application is deleted we delete the existing resources
19898            // as well and fall back to existing code in system partition
19899            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19900        } else {
19901            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19902            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19903                    outInfo, writeSettings, replacingPackage);
19904        }
19905
19906        // Take a note whether we deleted the package for all users
19907        if (outInfo != null) {
19908            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19909            if (outInfo.removedChildPackages != null) {
19910                synchronized (mPackages) {
19911                    final int childCount = outInfo.removedChildPackages.size();
19912                    for (int i = 0; i < childCount; i++) {
19913                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19914                        if (childInfo != null) {
19915                            childInfo.removedForAllUsers = mPackages.get(
19916                                    childInfo.removedPackage) == null;
19917                        }
19918                    }
19919                }
19920            }
19921            // If we uninstalled an update to a system app there may be some
19922            // child packages that appeared as they are declared in the system
19923            // app but were not declared in the update.
19924            if (isSystemApp(ps)) {
19925                synchronized (mPackages) {
19926                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19927                    final int childCount = (updatedPs.childPackageNames != null)
19928                            ? updatedPs.childPackageNames.size() : 0;
19929                    for (int i = 0; i < childCount; i++) {
19930                        String childPackageName = updatedPs.childPackageNames.get(i);
19931                        if (outInfo.removedChildPackages == null
19932                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19933                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19934                            if (childPs == null) {
19935                                continue;
19936                            }
19937                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19938                            installRes.name = childPackageName;
19939                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19940                            installRes.pkg = mPackages.get(childPackageName);
19941                            installRes.uid = childPs.pkg.applicationInfo.uid;
19942                            if (outInfo.appearedChildPackages == null) {
19943                                outInfo.appearedChildPackages = new ArrayMap<>();
19944                            }
19945                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19946                        }
19947                    }
19948                }
19949            }
19950        }
19951
19952        return ret;
19953    }
19954
19955    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19956        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19957                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19958        for (int nextUserId : userIds) {
19959            if (DEBUG_REMOVE) {
19960                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19961            }
19962            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19963                    false /*installed*/,
19964                    true /*stopped*/,
19965                    true /*notLaunched*/,
19966                    false /*hidden*/,
19967                    false /*suspended*/,
19968                    false /*instantApp*/,
19969                    null /*lastDisableAppCaller*/,
19970                    null /*enabledComponents*/,
19971                    null /*disabledComponents*/,
19972                    ps.readUserState(nextUserId).domainVerificationStatus,
19973                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19974        }
19975        mSettings.writeKernelMappingLPr(ps);
19976    }
19977
19978    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19979            PackageRemovedInfo outInfo) {
19980        final PackageParser.Package pkg;
19981        synchronized (mPackages) {
19982            pkg = mPackages.get(ps.name);
19983        }
19984
19985        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19986                : new int[] {userId};
19987        for (int nextUserId : userIds) {
19988            if (DEBUG_REMOVE) {
19989                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19990                        + nextUserId);
19991            }
19992
19993            destroyAppDataLIF(pkg, userId,
19994                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19995            destroyAppProfilesLIF(pkg, userId);
19996            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19997            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19998            schedulePackageCleaning(ps.name, nextUserId, false);
19999            synchronized (mPackages) {
20000                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20001                    scheduleWritePackageRestrictionsLocked(nextUserId);
20002                }
20003                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20004            }
20005        }
20006
20007        if (outInfo != null) {
20008            outInfo.removedPackage = ps.name;
20009            outInfo.installerPackageName = ps.installerPackageName;
20010            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20011            outInfo.removedAppId = ps.appId;
20012            outInfo.removedUsers = userIds;
20013            outInfo.broadcastUsers = userIds;
20014        }
20015
20016        return true;
20017    }
20018
20019    private final class ClearStorageConnection implements ServiceConnection {
20020        IMediaContainerService mContainerService;
20021
20022        @Override
20023        public void onServiceConnected(ComponentName name, IBinder service) {
20024            synchronized (this) {
20025                mContainerService = IMediaContainerService.Stub
20026                        .asInterface(Binder.allowBlocking(service));
20027                notifyAll();
20028            }
20029        }
20030
20031        @Override
20032        public void onServiceDisconnected(ComponentName name) {
20033        }
20034    }
20035
20036    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20037        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20038
20039        final boolean mounted;
20040        if (Environment.isExternalStorageEmulated()) {
20041            mounted = true;
20042        } else {
20043            final String status = Environment.getExternalStorageState();
20044
20045            mounted = status.equals(Environment.MEDIA_MOUNTED)
20046                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20047        }
20048
20049        if (!mounted) {
20050            return;
20051        }
20052
20053        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20054        int[] users;
20055        if (userId == UserHandle.USER_ALL) {
20056            users = sUserManager.getUserIds();
20057        } else {
20058            users = new int[] { userId };
20059        }
20060        final ClearStorageConnection conn = new ClearStorageConnection();
20061        if (mContext.bindServiceAsUser(
20062                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20063            try {
20064                for (int curUser : users) {
20065                    long timeout = SystemClock.uptimeMillis() + 5000;
20066                    synchronized (conn) {
20067                        long now;
20068                        while (conn.mContainerService == null &&
20069                                (now = SystemClock.uptimeMillis()) < timeout) {
20070                            try {
20071                                conn.wait(timeout - now);
20072                            } catch (InterruptedException e) {
20073                            }
20074                        }
20075                    }
20076                    if (conn.mContainerService == null) {
20077                        return;
20078                    }
20079
20080                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20081                    clearDirectory(conn.mContainerService,
20082                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20083                    if (allData) {
20084                        clearDirectory(conn.mContainerService,
20085                                userEnv.buildExternalStorageAppDataDirs(packageName));
20086                        clearDirectory(conn.mContainerService,
20087                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20088                    }
20089                }
20090            } finally {
20091                mContext.unbindService(conn);
20092            }
20093        }
20094    }
20095
20096    @Override
20097    public void clearApplicationProfileData(String packageName) {
20098        enforceSystemOrRoot("Only the system can clear all profile data");
20099
20100        final PackageParser.Package pkg;
20101        synchronized (mPackages) {
20102            pkg = mPackages.get(packageName);
20103        }
20104
20105        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20106            synchronized (mInstallLock) {
20107                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20108            }
20109        }
20110    }
20111
20112    @Override
20113    public void clearApplicationUserData(final String packageName,
20114            final IPackageDataObserver observer, final int userId) {
20115        mContext.enforceCallingOrSelfPermission(
20116                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20117
20118        final int callingUid = Binder.getCallingUid();
20119        enforceCrossUserPermission(callingUid, userId,
20120                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20121
20122        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20123        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
20124            return;
20125        }
20126        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20127            throw new SecurityException("Cannot clear data for a protected package: "
20128                    + packageName);
20129        }
20130        // Queue up an async operation since the package deletion may take a little while.
20131        mHandler.post(new Runnable() {
20132            public void run() {
20133                mHandler.removeCallbacks(this);
20134                final boolean succeeded;
20135                try (PackageFreezer freezer = freezePackage(packageName,
20136                        "clearApplicationUserData")) {
20137                    synchronized (mInstallLock) {
20138                        succeeded = clearApplicationUserDataLIF(packageName, userId);
20139                    }
20140                    clearExternalStorageDataSync(packageName, userId, true);
20141                    synchronized (mPackages) {
20142                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20143                                packageName, userId);
20144                    }
20145                }
20146                if (succeeded) {
20147                    // invoke DeviceStorageMonitor's update method to clear any notifications
20148                    DeviceStorageMonitorInternal dsm = LocalServices
20149                            .getService(DeviceStorageMonitorInternal.class);
20150                    if (dsm != null) {
20151                        dsm.checkMemory();
20152                    }
20153                }
20154                if(observer != null) {
20155                    try {
20156                        observer.onRemoveCompleted(packageName, succeeded);
20157                    } catch (RemoteException e) {
20158                        Log.i(TAG, "Observer no longer exists.");
20159                    }
20160                } //end if observer
20161            } //end run
20162        });
20163    }
20164
20165    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20166        if (packageName == null) {
20167            Slog.w(TAG, "Attempt to delete null packageName.");
20168            return false;
20169        }
20170
20171        // Try finding details about the requested package
20172        PackageParser.Package pkg;
20173        synchronized (mPackages) {
20174            pkg = mPackages.get(packageName);
20175            if (pkg == null) {
20176                final PackageSetting ps = mSettings.mPackages.get(packageName);
20177                if (ps != null) {
20178                    pkg = ps.pkg;
20179                }
20180            }
20181
20182            if (pkg == null) {
20183                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20184                return false;
20185            }
20186
20187            PackageSetting ps = (PackageSetting) pkg.mExtras;
20188            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20189        }
20190
20191        clearAppDataLIF(pkg, userId,
20192                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20193
20194        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20195        removeKeystoreDataIfNeeded(userId, appId);
20196
20197        UserManagerInternal umInternal = getUserManagerInternal();
20198        final int flags;
20199        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20200            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20201        } else if (umInternal.isUserRunning(userId)) {
20202            flags = StorageManager.FLAG_STORAGE_DE;
20203        } else {
20204            flags = 0;
20205        }
20206        prepareAppDataContentsLIF(pkg, userId, flags);
20207
20208        return true;
20209    }
20210
20211    /**
20212     * Reverts user permission state changes (permissions and flags) in
20213     * all packages for a given user.
20214     *
20215     * @param userId The device user for which to do a reset.
20216     */
20217    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20218        final int packageCount = mPackages.size();
20219        for (int i = 0; i < packageCount; i++) {
20220            PackageParser.Package pkg = mPackages.valueAt(i);
20221            PackageSetting ps = (PackageSetting) pkg.mExtras;
20222            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20223        }
20224    }
20225
20226    private void resetNetworkPolicies(int userId) {
20227        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20228    }
20229
20230    /**
20231     * Reverts user permission state changes (permissions and flags).
20232     *
20233     * @param ps The package for which to reset.
20234     * @param userId The device user for which to do a reset.
20235     */
20236    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20237            final PackageSetting ps, final int userId) {
20238        if (ps.pkg == null) {
20239            return;
20240        }
20241
20242        // These are flags that can change base on user actions.
20243        final int userSettableMask = FLAG_PERMISSION_USER_SET
20244                | FLAG_PERMISSION_USER_FIXED
20245                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20246                | FLAG_PERMISSION_REVIEW_REQUIRED;
20247
20248        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20249                | FLAG_PERMISSION_POLICY_FIXED;
20250
20251        boolean writeInstallPermissions = false;
20252        boolean writeRuntimePermissions = false;
20253
20254        final int permissionCount = ps.pkg.requestedPermissions.size();
20255        for (int i = 0; i < permissionCount; i++) {
20256            String permission = ps.pkg.requestedPermissions.get(i);
20257
20258            BasePermission bp = mSettings.mPermissions.get(permission);
20259            if (bp == null) {
20260                continue;
20261            }
20262
20263            // If shared user we just reset the state to which only this app contributed.
20264            if (ps.sharedUser != null) {
20265                boolean used = false;
20266                final int packageCount = ps.sharedUser.packages.size();
20267                for (int j = 0; j < packageCount; j++) {
20268                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20269                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20270                            && pkg.pkg.requestedPermissions.contains(permission)) {
20271                        used = true;
20272                        break;
20273                    }
20274                }
20275                if (used) {
20276                    continue;
20277                }
20278            }
20279
20280            PermissionsState permissionsState = ps.getPermissionsState();
20281
20282            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20283
20284            // Always clear the user settable flags.
20285            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20286                    bp.name) != null;
20287            // If permission review is enabled and this is a legacy app, mark the
20288            // permission as requiring a review as this is the initial state.
20289            int flags = 0;
20290            if (mPermissionReviewRequired
20291                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20292                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20293            }
20294            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20295                if (hasInstallState) {
20296                    writeInstallPermissions = true;
20297                } else {
20298                    writeRuntimePermissions = true;
20299                }
20300            }
20301
20302            // Below is only runtime permission handling.
20303            if (!bp.isRuntime()) {
20304                continue;
20305            }
20306
20307            // Never clobber system or policy.
20308            if ((oldFlags & policyOrSystemFlags) != 0) {
20309                continue;
20310            }
20311
20312            // If this permission was granted by default, make sure it is.
20313            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20314                if (permissionsState.grantRuntimePermission(bp, userId)
20315                        != PERMISSION_OPERATION_FAILURE) {
20316                    writeRuntimePermissions = true;
20317                }
20318            // If permission review is enabled the permissions for a legacy apps
20319            // are represented as constantly granted runtime ones, so don't revoke.
20320            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20321                // Otherwise, reset the permission.
20322                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20323                switch (revokeResult) {
20324                    case PERMISSION_OPERATION_SUCCESS:
20325                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20326                        writeRuntimePermissions = true;
20327                        final int appId = ps.appId;
20328                        mHandler.post(new Runnable() {
20329                            @Override
20330                            public void run() {
20331                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20332                            }
20333                        });
20334                    } break;
20335                }
20336            }
20337        }
20338
20339        // Synchronously write as we are taking permissions away.
20340        if (writeRuntimePermissions) {
20341            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20342        }
20343
20344        // Synchronously write as we are taking permissions away.
20345        if (writeInstallPermissions) {
20346            mSettings.writeLPr();
20347        }
20348    }
20349
20350    /**
20351     * Remove entries from the keystore daemon. Will only remove it if the
20352     * {@code appId} is valid.
20353     */
20354    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20355        if (appId < 0) {
20356            return;
20357        }
20358
20359        final KeyStore keyStore = KeyStore.getInstance();
20360        if (keyStore != null) {
20361            if (userId == UserHandle.USER_ALL) {
20362                for (final int individual : sUserManager.getUserIds()) {
20363                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20364                }
20365            } else {
20366                keyStore.clearUid(UserHandle.getUid(userId, appId));
20367            }
20368        } else {
20369            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20370        }
20371    }
20372
20373    @Override
20374    public void deleteApplicationCacheFiles(final String packageName,
20375            final IPackageDataObserver observer) {
20376        final int userId = UserHandle.getCallingUserId();
20377        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20378    }
20379
20380    @Override
20381    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20382            final IPackageDataObserver observer) {
20383        final int callingUid = Binder.getCallingUid();
20384        mContext.enforceCallingOrSelfPermission(
20385                android.Manifest.permission.DELETE_CACHE_FILES, null);
20386        enforceCrossUserPermission(callingUid, userId,
20387                /* requireFullPermission= */ true, /* checkShell= */ false,
20388                "delete application cache files");
20389        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20390                android.Manifest.permission.ACCESS_INSTANT_APPS);
20391
20392        final PackageParser.Package pkg;
20393        synchronized (mPackages) {
20394            pkg = mPackages.get(packageName);
20395        }
20396
20397        // Queue up an async operation since the package deletion may take a little while.
20398        mHandler.post(new Runnable() {
20399            public void run() {
20400                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20401                boolean doClearData = true;
20402                if (ps != null) {
20403                    final boolean targetIsInstantApp =
20404                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20405                    doClearData = !targetIsInstantApp
20406                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20407                }
20408                if (doClearData) {
20409                    synchronized (mInstallLock) {
20410                        final int flags = StorageManager.FLAG_STORAGE_DE
20411                                | StorageManager.FLAG_STORAGE_CE;
20412                        // We're only clearing cache files, so we don't care if the
20413                        // app is unfrozen and still able to run
20414                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20415                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20416                    }
20417                    clearExternalStorageDataSync(packageName, userId, false);
20418                }
20419                if (observer != null) {
20420                    try {
20421                        observer.onRemoveCompleted(packageName, true);
20422                    } catch (RemoteException e) {
20423                        Log.i(TAG, "Observer no longer exists.");
20424                    }
20425                }
20426            }
20427        });
20428    }
20429
20430    @Override
20431    public void getPackageSizeInfo(final String packageName, int userHandle,
20432            final IPackageStatsObserver observer) {
20433        throw new UnsupportedOperationException(
20434                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20435    }
20436
20437    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20438        final PackageSetting ps;
20439        synchronized (mPackages) {
20440            ps = mSettings.mPackages.get(packageName);
20441            if (ps == null) {
20442                Slog.w(TAG, "Failed to find settings for " + packageName);
20443                return false;
20444            }
20445        }
20446
20447        final String[] packageNames = { packageName };
20448        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20449        final String[] codePaths = { ps.codePathString };
20450
20451        try {
20452            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20453                    ps.appId, ceDataInodes, codePaths, stats);
20454
20455            // For now, ignore code size of packages on system partition
20456            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20457                stats.codeSize = 0;
20458            }
20459
20460            // External clients expect these to be tracked separately
20461            stats.dataSize -= stats.cacheSize;
20462
20463        } catch (InstallerException e) {
20464            Slog.w(TAG, String.valueOf(e));
20465            return false;
20466        }
20467
20468        return true;
20469    }
20470
20471    private int getUidTargetSdkVersionLockedLPr(int uid) {
20472        Object obj = mSettings.getUserIdLPr(uid);
20473        if (obj instanceof SharedUserSetting) {
20474            final SharedUserSetting sus = (SharedUserSetting) obj;
20475            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20476            final Iterator<PackageSetting> it = sus.packages.iterator();
20477            while (it.hasNext()) {
20478                final PackageSetting ps = it.next();
20479                if (ps.pkg != null) {
20480                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20481                    if (v < vers) vers = v;
20482                }
20483            }
20484            return vers;
20485        } else if (obj instanceof PackageSetting) {
20486            final PackageSetting ps = (PackageSetting) obj;
20487            if (ps.pkg != null) {
20488                return ps.pkg.applicationInfo.targetSdkVersion;
20489            }
20490        }
20491        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20492    }
20493
20494    @Override
20495    public void addPreferredActivity(IntentFilter filter, int match,
20496            ComponentName[] set, ComponentName activity, int userId) {
20497        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20498                "Adding preferred");
20499    }
20500
20501    private void addPreferredActivityInternal(IntentFilter filter, int match,
20502            ComponentName[] set, ComponentName activity, boolean always, int userId,
20503            String opname) {
20504        // writer
20505        int callingUid = Binder.getCallingUid();
20506        enforceCrossUserPermission(callingUid, userId,
20507                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20508        if (filter.countActions() == 0) {
20509            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20510            return;
20511        }
20512        synchronized (mPackages) {
20513            if (mContext.checkCallingOrSelfPermission(
20514                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20515                    != PackageManager.PERMISSION_GRANTED) {
20516                if (getUidTargetSdkVersionLockedLPr(callingUid)
20517                        < Build.VERSION_CODES.FROYO) {
20518                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20519                            + callingUid);
20520                    return;
20521                }
20522                mContext.enforceCallingOrSelfPermission(
20523                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20524            }
20525
20526            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20527            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20528                    + userId + ":");
20529            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20530            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20531            scheduleWritePackageRestrictionsLocked(userId);
20532            postPreferredActivityChangedBroadcast(userId);
20533        }
20534    }
20535
20536    private void postPreferredActivityChangedBroadcast(int userId) {
20537        mHandler.post(() -> {
20538            final IActivityManager am = ActivityManager.getService();
20539            if (am == null) {
20540                return;
20541            }
20542
20543            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20544            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20545            try {
20546                am.broadcastIntent(null, intent, null, null,
20547                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20548                        null, false, false, userId);
20549            } catch (RemoteException e) {
20550            }
20551        });
20552    }
20553
20554    @Override
20555    public void replacePreferredActivity(IntentFilter filter, int match,
20556            ComponentName[] set, ComponentName activity, int userId) {
20557        if (filter.countActions() != 1) {
20558            throw new IllegalArgumentException(
20559                    "replacePreferredActivity expects filter to have only 1 action.");
20560        }
20561        if (filter.countDataAuthorities() != 0
20562                || filter.countDataPaths() != 0
20563                || filter.countDataSchemes() > 1
20564                || filter.countDataTypes() != 0) {
20565            throw new IllegalArgumentException(
20566                    "replacePreferredActivity expects filter to have no data authorities, " +
20567                    "paths, or types; and at most one scheme.");
20568        }
20569
20570        final int callingUid = Binder.getCallingUid();
20571        enforceCrossUserPermission(callingUid, userId,
20572                true /* requireFullPermission */, false /* checkShell */,
20573                "replace preferred activity");
20574        synchronized (mPackages) {
20575            if (mContext.checkCallingOrSelfPermission(
20576                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20577                    != PackageManager.PERMISSION_GRANTED) {
20578                if (getUidTargetSdkVersionLockedLPr(callingUid)
20579                        < Build.VERSION_CODES.FROYO) {
20580                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20581                            + Binder.getCallingUid());
20582                    return;
20583                }
20584                mContext.enforceCallingOrSelfPermission(
20585                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20586            }
20587
20588            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20589            if (pir != null) {
20590                // Get all of the existing entries that exactly match this filter.
20591                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20592                if (existing != null && existing.size() == 1) {
20593                    PreferredActivity cur = existing.get(0);
20594                    if (DEBUG_PREFERRED) {
20595                        Slog.i(TAG, "Checking replace of preferred:");
20596                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20597                        if (!cur.mPref.mAlways) {
20598                            Slog.i(TAG, "  -- CUR; not mAlways!");
20599                        } else {
20600                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20601                            Slog.i(TAG, "  -- CUR: mSet="
20602                                    + Arrays.toString(cur.mPref.mSetComponents));
20603                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20604                            Slog.i(TAG, "  -- NEW: mMatch="
20605                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20606                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20607                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20608                        }
20609                    }
20610                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20611                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20612                            && cur.mPref.sameSet(set)) {
20613                        // Setting the preferred activity to what it happens to be already
20614                        if (DEBUG_PREFERRED) {
20615                            Slog.i(TAG, "Replacing with same preferred activity "
20616                                    + cur.mPref.mShortComponent + " for user "
20617                                    + userId + ":");
20618                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20619                        }
20620                        return;
20621                    }
20622                }
20623
20624                if (existing != null) {
20625                    if (DEBUG_PREFERRED) {
20626                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20627                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20628                    }
20629                    for (int i = 0; i < existing.size(); i++) {
20630                        PreferredActivity pa = existing.get(i);
20631                        if (DEBUG_PREFERRED) {
20632                            Slog.i(TAG, "Removing existing preferred activity "
20633                                    + pa.mPref.mComponent + ":");
20634                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20635                        }
20636                        pir.removeFilter(pa);
20637                    }
20638                }
20639            }
20640            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20641                    "Replacing preferred");
20642        }
20643    }
20644
20645    @Override
20646    public void clearPackagePreferredActivities(String packageName) {
20647        final int callingUid = Binder.getCallingUid();
20648        if (getInstantAppPackageName(callingUid) != null) {
20649            return;
20650        }
20651        // writer
20652        synchronized (mPackages) {
20653            PackageParser.Package pkg = mPackages.get(packageName);
20654            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20655                if (mContext.checkCallingOrSelfPermission(
20656                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20657                        != PackageManager.PERMISSION_GRANTED) {
20658                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20659                            < Build.VERSION_CODES.FROYO) {
20660                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20661                                + callingUid);
20662                        return;
20663                    }
20664                    mContext.enforceCallingOrSelfPermission(
20665                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20666                }
20667            }
20668            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20669            if (ps != null
20670                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20671                return;
20672            }
20673            int user = UserHandle.getCallingUserId();
20674            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20675                scheduleWritePackageRestrictionsLocked(user);
20676            }
20677        }
20678    }
20679
20680    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20681    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20682        ArrayList<PreferredActivity> removed = null;
20683        boolean changed = false;
20684        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20685            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20686            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20687            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20688                continue;
20689            }
20690            Iterator<PreferredActivity> it = pir.filterIterator();
20691            while (it.hasNext()) {
20692                PreferredActivity pa = it.next();
20693                // Mark entry for removal only if it matches the package name
20694                // and the entry is of type "always".
20695                if (packageName == null ||
20696                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20697                                && pa.mPref.mAlways)) {
20698                    if (removed == null) {
20699                        removed = new ArrayList<PreferredActivity>();
20700                    }
20701                    removed.add(pa);
20702                }
20703            }
20704            if (removed != null) {
20705                for (int j=0; j<removed.size(); j++) {
20706                    PreferredActivity pa = removed.get(j);
20707                    pir.removeFilter(pa);
20708                }
20709                changed = true;
20710            }
20711        }
20712        if (changed) {
20713            postPreferredActivityChangedBroadcast(userId);
20714        }
20715        return changed;
20716    }
20717
20718    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20719    private void clearIntentFilterVerificationsLPw(int userId) {
20720        final int packageCount = mPackages.size();
20721        for (int i = 0; i < packageCount; i++) {
20722            PackageParser.Package pkg = mPackages.valueAt(i);
20723            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20724        }
20725    }
20726
20727    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20728    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20729        if (userId == UserHandle.USER_ALL) {
20730            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20731                    sUserManager.getUserIds())) {
20732                for (int oneUserId : sUserManager.getUserIds()) {
20733                    scheduleWritePackageRestrictionsLocked(oneUserId);
20734                }
20735            }
20736        } else {
20737            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20738                scheduleWritePackageRestrictionsLocked(userId);
20739            }
20740        }
20741    }
20742
20743    /** Clears state for all users, and touches intent filter verification policy */
20744    void clearDefaultBrowserIfNeeded(String packageName) {
20745        for (int oneUserId : sUserManager.getUserIds()) {
20746            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20747        }
20748    }
20749
20750    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20751        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20752        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20753            if (packageName.equals(defaultBrowserPackageName)) {
20754                setDefaultBrowserPackageName(null, userId);
20755            }
20756        }
20757    }
20758
20759    @Override
20760    public void resetApplicationPreferences(int userId) {
20761        mContext.enforceCallingOrSelfPermission(
20762                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20763        final long identity = Binder.clearCallingIdentity();
20764        // writer
20765        try {
20766            synchronized (mPackages) {
20767                clearPackagePreferredActivitiesLPw(null, userId);
20768                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20769                // TODO: We have to reset the default SMS and Phone. This requires
20770                // significant refactoring to keep all default apps in the package
20771                // manager (cleaner but more work) or have the services provide
20772                // callbacks to the package manager to request a default app reset.
20773                applyFactoryDefaultBrowserLPw(userId);
20774                clearIntentFilterVerificationsLPw(userId);
20775                primeDomainVerificationsLPw(userId);
20776                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20777                scheduleWritePackageRestrictionsLocked(userId);
20778            }
20779            resetNetworkPolicies(userId);
20780        } finally {
20781            Binder.restoreCallingIdentity(identity);
20782        }
20783    }
20784
20785    @Override
20786    public int getPreferredActivities(List<IntentFilter> outFilters,
20787            List<ComponentName> outActivities, String packageName) {
20788        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20789            return 0;
20790        }
20791        int num = 0;
20792        final int userId = UserHandle.getCallingUserId();
20793        // reader
20794        synchronized (mPackages) {
20795            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20796            if (pir != null) {
20797                final Iterator<PreferredActivity> it = pir.filterIterator();
20798                while (it.hasNext()) {
20799                    final PreferredActivity pa = it.next();
20800                    if (packageName == null
20801                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20802                                    && pa.mPref.mAlways)) {
20803                        if (outFilters != null) {
20804                            outFilters.add(new IntentFilter(pa));
20805                        }
20806                        if (outActivities != null) {
20807                            outActivities.add(pa.mPref.mComponent);
20808                        }
20809                    }
20810                }
20811            }
20812        }
20813
20814        return num;
20815    }
20816
20817    @Override
20818    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20819            int userId) {
20820        int callingUid = Binder.getCallingUid();
20821        if (callingUid != Process.SYSTEM_UID) {
20822            throw new SecurityException(
20823                    "addPersistentPreferredActivity can only be run by the system");
20824        }
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            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20831                    ":");
20832            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20833            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20834                    new PersistentPreferredActivity(filter, activity));
20835            scheduleWritePackageRestrictionsLocked(userId);
20836            postPreferredActivityChangedBroadcast(userId);
20837        }
20838    }
20839
20840    @Override
20841    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20842        int callingUid = Binder.getCallingUid();
20843        if (callingUid != Process.SYSTEM_UID) {
20844            throw new SecurityException(
20845                    "clearPackagePersistentPreferredActivities can only be run by the system");
20846        }
20847        ArrayList<PersistentPreferredActivity> removed = null;
20848        boolean changed = false;
20849        synchronized (mPackages) {
20850            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20851                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20852                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20853                        .valueAt(i);
20854                if (userId != thisUserId) {
20855                    continue;
20856                }
20857                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20858                while (it.hasNext()) {
20859                    PersistentPreferredActivity ppa = it.next();
20860                    // Mark entry for removal only if it matches the package name.
20861                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20862                        if (removed == null) {
20863                            removed = new ArrayList<PersistentPreferredActivity>();
20864                        }
20865                        removed.add(ppa);
20866                    }
20867                }
20868                if (removed != null) {
20869                    for (int j=0; j<removed.size(); j++) {
20870                        PersistentPreferredActivity ppa = removed.get(j);
20871                        ppir.removeFilter(ppa);
20872                    }
20873                    changed = true;
20874                }
20875            }
20876
20877            if (changed) {
20878                scheduleWritePackageRestrictionsLocked(userId);
20879                postPreferredActivityChangedBroadcast(userId);
20880            }
20881        }
20882    }
20883
20884    /**
20885     * Common machinery for picking apart a restored XML blob and passing
20886     * it to a caller-supplied functor to be applied to the running system.
20887     */
20888    private void restoreFromXml(XmlPullParser parser, int userId,
20889            String expectedStartTag, BlobXmlRestorer functor)
20890            throws IOException, XmlPullParserException {
20891        int type;
20892        while ((type = parser.next()) != XmlPullParser.START_TAG
20893                && type != XmlPullParser.END_DOCUMENT) {
20894        }
20895        if (type != XmlPullParser.START_TAG) {
20896            // oops didn't find a start tag?!
20897            if (DEBUG_BACKUP) {
20898                Slog.e(TAG, "Didn't find start tag during restore");
20899            }
20900            return;
20901        }
20902Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20903        // this is supposed to be TAG_PREFERRED_BACKUP
20904        if (!expectedStartTag.equals(parser.getName())) {
20905            if (DEBUG_BACKUP) {
20906                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20907            }
20908            return;
20909        }
20910
20911        // skip interfering stuff, then we're aligned with the backing implementation
20912        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20913Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20914        functor.apply(parser, userId);
20915    }
20916
20917    private interface BlobXmlRestorer {
20918        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20919    }
20920
20921    /**
20922     * Non-Binder method, support for the backup/restore mechanism: write the
20923     * full set of preferred activities in its canonical XML format.  Returns the
20924     * XML output as a byte array, or null if there is none.
20925     */
20926    @Override
20927    public byte[] getPreferredActivityBackup(int userId) {
20928        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20929            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20930        }
20931
20932        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20933        try {
20934            final XmlSerializer serializer = new FastXmlSerializer();
20935            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20936            serializer.startDocument(null, true);
20937            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20938
20939            synchronized (mPackages) {
20940                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20941            }
20942
20943            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20944            serializer.endDocument();
20945            serializer.flush();
20946        } catch (Exception e) {
20947            if (DEBUG_BACKUP) {
20948                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20949            }
20950            return null;
20951        }
20952
20953        return dataStream.toByteArray();
20954    }
20955
20956    @Override
20957    public void restorePreferredActivities(byte[] backup, int userId) {
20958        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20959            throw new SecurityException("Only the system may call restorePreferredActivities()");
20960        }
20961
20962        try {
20963            final XmlPullParser parser = Xml.newPullParser();
20964            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20965            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20966                    new BlobXmlRestorer() {
20967                        @Override
20968                        public void apply(XmlPullParser parser, int userId)
20969                                throws XmlPullParserException, IOException {
20970                            synchronized (mPackages) {
20971                                mSettings.readPreferredActivitiesLPw(parser, userId);
20972                            }
20973                        }
20974                    } );
20975        } catch (Exception e) {
20976            if (DEBUG_BACKUP) {
20977                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20978            }
20979        }
20980    }
20981
20982    /**
20983     * Non-Binder method, support for the backup/restore mechanism: write the
20984     * default browser (etc) settings in its canonical XML format.  Returns the default
20985     * browser XML representation as a byte array, or null if there is none.
20986     */
20987    @Override
20988    public byte[] getDefaultAppsBackup(int userId) {
20989        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20990            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20991        }
20992
20993        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20994        try {
20995            final XmlSerializer serializer = new FastXmlSerializer();
20996            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20997            serializer.startDocument(null, true);
20998            serializer.startTag(null, TAG_DEFAULT_APPS);
20999
21000            synchronized (mPackages) {
21001                mSettings.writeDefaultAppsLPr(serializer, userId);
21002            }
21003
21004            serializer.endTag(null, TAG_DEFAULT_APPS);
21005            serializer.endDocument();
21006            serializer.flush();
21007        } catch (Exception e) {
21008            if (DEBUG_BACKUP) {
21009                Slog.e(TAG, "Unable to write default apps for backup", e);
21010            }
21011            return null;
21012        }
21013
21014        return dataStream.toByteArray();
21015    }
21016
21017    @Override
21018    public void restoreDefaultApps(byte[] backup, int userId) {
21019        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21020            throw new SecurityException("Only the system may call restoreDefaultApps()");
21021        }
21022
21023        try {
21024            final XmlPullParser parser = Xml.newPullParser();
21025            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21026            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21027                    new BlobXmlRestorer() {
21028                        @Override
21029                        public void apply(XmlPullParser parser, int userId)
21030                                throws XmlPullParserException, IOException {
21031                            synchronized (mPackages) {
21032                                mSettings.readDefaultAppsLPw(parser, userId);
21033                            }
21034                        }
21035                    } );
21036        } catch (Exception e) {
21037            if (DEBUG_BACKUP) {
21038                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21039            }
21040        }
21041    }
21042
21043    @Override
21044    public byte[] getIntentFilterVerificationBackup(int userId) {
21045        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21046            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21047        }
21048
21049        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21050        try {
21051            final XmlSerializer serializer = new FastXmlSerializer();
21052            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21053            serializer.startDocument(null, true);
21054            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21055
21056            synchronized (mPackages) {
21057                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21058            }
21059
21060            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21061            serializer.endDocument();
21062            serializer.flush();
21063        } catch (Exception e) {
21064            if (DEBUG_BACKUP) {
21065                Slog.e(TAG, "Unable to write default apps for backup", e);
21066            }
21067            return null;
21068        }
21069
21070        return dataStream.toByteArray();
21071    }
21072
21073    @Override
21074    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21075        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21076            throw new SecurityException("Only the system may call restorePreferredActivities()");
21077        }
21078
21079        try {
21080            final XmlPullParser parser = Xml.newPullParser();
21081            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21082            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21083                    new BlobXmlRestorer() {
21084                        @Override
21085                        public void apply(XmlPullParser parser, int userId)
21086                                throws XmlPullParserException, IOException {
21087                            synchronized (mPackages) {
21088                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21089                                mSettings.writeLPr();
21090                            }
21091                        }
21092                    } );
21093        } catch (Exception e) {
21094            if (DEBUG_BACKUP) {
21095                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21096            }
21097        }
21098    }
21099
21100    @Override
21101    public byte[] getPermissionGrantBackup(int userId) {
21102        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21103            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21104        }
21105
21106        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21107        try {
21108            final XmlSerializer serializer = new FastXmlSerializer();
21109            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21110            serializer.startDocument(null, true);
21111            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21112
21113            synchronized (mPackages) {
21114                serializeRuntimePermissionGrantsLPr(serializer, userId);
21115            }
21116
21117            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21118            serializer.endDocument();
21119            serializer.flush();
21120        } catch (Exception e) {
21121            if (DEBUG_BACKUP) {
21122                Slog.e(TAG, "Unable to write default apps for backup", e);
21123            }
21124            return null;
21125        }
21126
21127        return dataStream.toByteArray();
21128    }
21129
21130    @Override
21131    public void restorePermissionGrants(byte[] backup, int userId) {
21132        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21133            throw new SecurityException("Only the system may call restorePermissionGrants()");
21134        }
21135
21136        try {
21137            final XmlPullParser parser = Xml.newPullParser();
21138            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21139            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21140                    new BlobXmlRestorer() {
21141                        @Override
21142                        public void apply(XmlPullParser parser, int userId)
21143                                throws XmlPullParserException, IOException {
21144                            synchronized (mPackages) {
21145                                processRestoredPermissionGrantsLPr(parser, userId);
21146                            }
21147                        }
21148                    } );
21149        } catch (Exception e) {
21150            if (DEBUG_BACKUP) {
21151                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21152            }
21153        }
21154    }
21155
21156    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21157            throws IOException {
21158        serializer.startTag(null, TAG_ALL_GRANTS);
21159
21160        final int N = mSettings.mPackages.size();
21161        for (int i = 0; i < N; i++) {
21162            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21163            boolean pkgGrantsKnown = false;
21164
21165            PermissionsState packagePerms = ps.getPermissionsState();
21166
21167            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21168                final int grantFlags = state.getFlags();
21169                // only look at grants that are not system/policy fixed
21170                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21171                    final boolean isGranted = state.isGranted();
21172                    // And only back up the user-twiddled state bits
21173                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21174                        final String packageName = mSettings.mPackages.keyAt(i);
21175                        if (!pkgGrantsKnown) {
21176                            serializer.startTag(null, TAG_GRANT);
21177                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21178                            pkgGrantsKnown = true;
21179                        }
21180
21181                        final boolean userSet =
21182                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21183                        final boolean userFixed =
21184                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21185                        final boolean revoke =
21186                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21187
21188                        serializer.startTag(null, TAG_PERMISSION);
21189                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21190                        if (isGranted) {
21191                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21192                        }
21193                        if (userSet) {
21194                            serializer.attribute(null, ATTR_USER_SET, "true");
21195                        }
21196                        if (userFixed) {
21197                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21198                        }
21199                        if (revoke) {
21200                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21201                        }
21202                        serializer.endTag(null, TAG_PERMISSION);
21203                    }
21204                }
21205            }
21206
21207            if (pkgGrantsKnown) {
21208                serializer.endTag(null, TAG_GRANT);
21209            }
21210        }
21211
21212        serializer.endTag(null, TAG_ALL_GRANTS);
21213    }
21214
21215    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21216            throws XmlPullParserException, IOException {
21217        String pkgName = null;
21218        int outerDepth = parser.getDepth();
21219        int type;
21220        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21221                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21222            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21223                continue;
21224            }
21225
21226            final String tagName = parser.getName();
21227            if (tagName.equals(TAG_GRANT)) {
21228                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21229                if (DEBUG_BACKUP) {
21230                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21231                }
21232            } else if (tagName.equals(TAG_PERMISSION)) {
21233
21234                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21235                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21236
21237                int newFlagSet = 0;
21238                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21239                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21240                }
21241                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21242                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21243                }
21244                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21245                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21246                }
21247                if (DEBUG_BACKUP) {
21248                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21249                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21250                }
21251                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21252                if (ps != null) {
21253                    // Already installed so we apply the grant immediately
21254                    if (DEBUG_BACKUP) {
21255                        Slog.v(TAG, "        + already installed; applying");
21256                    }
21257                    PermissionsState perms = ps.getPermissionsState();
21258                    BasePermission bp = mSettings.mPermissions.get(permName);
21259                    if (bp != null) {
21260                        if (isGranted) {
21261                            perms.grantRuntimePermission(bp, userId);
21262                        }
21263                        if (newFlagSet != 0) {
21264                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21265                        }
21266                    }
21267                } else {
21268                    // Need to wait for post-restore install to apply the grant
21269                    if (DEBUG_BACKUP) {
21270                        Slog.v(TAG, "        - not yet installed; saving for later");
21271                    }
21272                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21273                            isGranted, newFlagSet, userId);
21274                }
21275            } else {
21276                PackageManagerService.reportSettingsProblem(Log.WARN,
21277                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21278                XmlUtils.skipCurrentTag(parser);
21279            }
21280        }
21281
21282        scheduleWriteSettingsLocked();
21283        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21284    }
21285
21286    @Override
21287    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21288            int sourceUserId, int targetUserId, int flags) {
21289        mContext.enforceCallingOrSelfPermission(
21290                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21291        int callingUid = Binder.getCallingUid();
21292        enforceOwnerRights(ownerPackage, callingUid);
21293        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21294        if (intentFilter.countActions() == 0) {
21295            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21296            return;
21297        }
21298        synchronized (mPackages) {
21299            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21300                    ownerPackage, targetUserId, flags);
21301            CrossProfileIntentResolver resolver =
21302                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21303            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21304            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21305            if (existing != null) {
21306                int size = existing.size();
21307                for (int i = 0; i < size; i++) {
21308                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21309                        return;
21310                    }
21311                }
21312            }
21313            resolver.addFilter(newFilter);
21314            scheduleWritePackageRestrictionsLocked(sourceUserId);
21315        }
21316    }
21317
21318    @Override
21319    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21320        mContext.enforceCallingOrSelfPermission(
21321                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21322        final int callingUid = Binder.getCallingUid();
21323        enforceOwnerRights(ownerPackage, callingUid);
21324        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21325        synchronized (mPackages) {
21326            CrossProfileIntentResolver resolver =
21327                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21328            ArraySet<CrossProfileIntentFilter> set =
21329                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21330            for (CrossProfileIntentFilter filter : set) {
21331                if (filter.getOwnerPackage().equals(ownerPackage)) {
21332                    resolver.removeFilter(filter);
21333                }
21334            }
21335            scheduleWritePackageRestrictionsLocked(sourceUserId);
21336        }
21337    }
21338
21339    // Enforcing that callingUid is owning pkg on userId
21340    private void enforceOwnerRights(String pkg, int callingUid) {
21341        // The system owns everything.
21342        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21343            return;
21344        }
21345        final int callingUserId = UserHandle.getUserId(callingUid);
21346        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21347        if (pi == null) {
21348            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21349                    + callingUserId);
21350        }
21351        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21352            throw new SecurityException("Calling uid " + callingUid
21353                    + " does not own package " + pkg);
21354        }
21355    }
21356
21357    @Override
21358    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21359        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21360            return null;
21361        }
21362        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21363    }
21364
21365    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21366        UserManagerService ums = UserManagerService.getInstance();
21367        if (ums != null) {
21368            final UserInfo parent = ums.getProfileParent(userId);
21369            final int launcherUid = (parent != null) ? parent.id : userId;
21370            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21371            if (launcherComponent != null) {
21372                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21373                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21374                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21375                        .setPackage(launcherComponent.getPackageName());
21376                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21377            }
21378        }
21379    }
21380
21381    /**
21382     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21383     * then reports the most likely home activity or null if there are more than one.
21384     */
21385    private ComponentName getDefaultHomeActivity(int userId) {
21386        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21387        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21388        if (cn != null) {
21389            return cn;
21390        }
21391
21392        // Find the launcher with the highest priority and return that component if there are no
21393        // other home activity with the same priority.
21394        int lastPriority = Integer.MIN_VALUE;
21395        ComponentName lastComponent = null;
21396        final int size = allHomeCandidates.size();
21397        for (int i = 0; i < size; i++) {
21398            final ResolveInfo ri = allHomeCandidates.get(i);
21399            if (ri.priority > lastPriority) {
21400                lastComponent = ri.activityInfo.getComponentName();
21401                lastPriority = ri.priority;
21402            } else if (ri.priority == lastPriority) {
21403                // Two components found with same priority.
21404                lastComponent = null;
21405            }
21406        }
21407        return lastComponent;
21408    }
21409
21410    private Intent getHomeIntent() {
21411        Intent intent = new Intent(Intent.ACTION_MAIN);
21412        intent.addCategory(Intent.CATEGORY_HOME);
21413        intent.addCategory(Intent.CATEGORY_DEFAULT);
21414        return intent;
21415    }
21416
21417    private IntentFilter getHomeFilter() {
21418        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21419        filter.addCategory(Intent.CATEGORY_HOME);
21420        filter.addCategory(Intent.CATEGORY_DEFAULT);
21421        return filter;
21422    }
21423
21424    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21425            int userId) {
21426        Intent intent  = getHomeIntent();
21427        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21428                PackageManager.GET_META_DATA, userId);
21429        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21430                true, false, false, userId);
21431
21432        allHomeCandidates.clear();
21433        if (list != null) {
21434            for (ResolveInfo ri : list) {
21435                allHomeCandidates.add(ri);
21436            }
21437        }
21438        return (preferred == null || preferred.activityInfo == null)
21439                ? null
21440                : new ComponentName(preferred.activityInfo.packageName,
21441                        preferred.activityInfo.name);
21442    }
21443
21444    @Override
21445    public void setHomeActivity(ComponentName comp, int userId) {
21446        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21447            return;
21448        }
21449        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21450        getHomeActivitiesAsUser(homeActivities, userId);
21451
21452        boolean found = false;
21453
21454        final int size = homeActivities.size();
21455        final ComponentName[] set = new ComponentName[size];
21456        for (int i = 0; i < size; i++) {
21457            final ResolveInfo candidate = homeActivities.get(i);
21458            final ActivityInfo info = candidate.activityInfo;
21459            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21460            set[i] = activityName;
21461            if (!found && activityName.equals(comp)) {
21462                found = true;
21463            }
21464        }
21465        if (!found) {
21466            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21467                    + userId);
21468        }
21469        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21470                set, comp, userId);
21471    }
21472
21473    private @Nullable String getSetupWizardPackageName() {
21474        final Intent intent = new Intent(Intent.ACTION_MAIN);
21475        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21476
21477        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21478                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21479                        | MATCH_DISABLED_COMPONENTS,
21480                UserHandle.myUserId());
21481        if (matches.size() == 1) {
21482            return matches.get(0).getComponentInfo().packageName;
21483        } else {
21484            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21485                    + ": matches=" + matches);
21486            return null;
21487        }
21488    }
21489
21490    private @Nullable String getStorageManagerPackageName() {
21491        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21492
21493        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21494                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21495                        | MATCH_DISABLED_COMPONENTS,
21496                UserHandle.myUserId());
21497        if (matches.size() == 1) {
21498            return matches.get(0).getComponentInfo().packageName;
21499        } else {
21500            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21501                    + matches.size() + ": matches=" + matches);
21502            return null;
21503        }
21504    }
21505
21506    @Override
21507    public void setApplicationEnabledSetting(String appPackageName,
21508            int newState, int flags, int userId, String callingPackage) {
21509        if (!sUserManager.exists(userId)) return;
21510        if (callingPackage == null) {
21511            callingPackage = Integer.toString(Binder.getCallingUid());
21512        }
21513        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21514    }
21515
21516    @Override
21517    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21518        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21519        synchronized (mPackages) {
21520            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21521            if (pkgSetting != null) {
21522                pkgSetting.setUpdateAvailable(updateAvailable);
21523            }
21524        }
21525    }
21526
21527    @Override
21528    public void setComponentEnabledSetting(ComponentName componentName,
21529            int newState, int flags, int userId) {
21530        if (!sUserManager.exists(userId)) return;
21531        setEnabledSetting(componentName.getPackageName(),
21532                componentName.getClassName(), newState, flags, userId, null);
21533    }
21534
21535    private void setEnabledSetting(final String packageName, String className, int newState,
21536            final int flags, int userId, String callingPackage) {
21537        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21538              || newState == COMPONENT_ENABLED_STATE_ENABLED
21539              || newState == COMPONENT_ENABLED_STATE_DISABLED
21540              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21541              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21542            throw new IllegalArgumentException("Invalid new component state: "
21543                    + newState);
21544        }
21545        PackageSetting pkgSetting;
21546        final int callingUid = Binder.getCallingUid();
21547        final int permission;
21548        if (callingUid == Process.SYSTEM_UID) {
21549            permission = PackageManager.PERMISSION_GRANTED;
21550        } else {
21551            permission = mContext.checkCallingOrSelfPermission(
21552                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21553        }
21554        enforceCrossUserPermission(callingUid, userId,
21555                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21556        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21557        boolean sendNow = false;
21558        boolean isApp = (className == null);
21559        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21560        String componentName = isApp ? packageName : className;
21561        int packageUid = -1;
21562        ArrayList<String> components;
21563
21564        // reader
21565        synchronized (mPackages) {
21566            pkgSetting = mSettings.mPackages.get(packageName);
21567            if (pkgSetting == null) {
21568                if (!isCallerInstantApp) {
21569                    if (className == null) {
21570                        throw new IllegalArgumentException("Unknown package: " + packageName);
21571                    }
21572                    throw new IllegalArgumentException(
21573                            "Unknown component: " + packageName + "/" + className);
21574                } else {
21575                    // throw SecurityException to prevent leaking package information
21576                    throw new SecurityException(
21577                            "Attempt to change component state; "
21578                            + "pid=" + Binder.getCallingPid()
21579                            + ", uid=" + callingUid
21580                            + (className == null
21581                                    ? ", package=" + packageName
21582                                    : ", component=" + packageName + "/" + className));
21583                }
21584            }
21585        }
21586
21587        // Limit who can change which apps
21588        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21589            // Don't allow apps that don't have permission to modify other apps
21590            if (!allowedByPermission
21591                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21592                throw new SecurityException(
21593                        "Attempt to change component state; "
21594                        + "pid=" + Binder.getCallingPid()
21595                        + ", uid=" + callingUid
21596                        + (className == null
21597                                ? ", package=" + packageName
21598                                : ", component=" + packageName + "/" + className));
21599            }
21600            // Don't allow changing protected packages.
21601            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21602                throw new SecurityException("Cannot disable a protected package: " + packageName);
21603            }
21604        }
21605
21606        synchronized (mPackages) {
21607            if (callingUid == Process.SHELL_UID
21608                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21609                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21610                // unless it is a test package.
21611                int oldState = pkgSetting.getEnabled(userId);
21612                if (className == null
21613                    &&
21614                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21615                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21616                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21617                    &&
21618                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21619                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21620                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21621                    // ok
21622                } else {
21623                    throw new SecurityException(
21624                            "Shell cannot change component state for " + packageName + "/"
21625                            + className + " to " + newState);
21626                }
21627            }
21628            if (className == null) {
21629                // We're dealing with an application/package level state change
21630                if (pkgSetting.getEnabled(userId) == newState) {
21631                    // Nothing to do
21632                    return;
21633                }
21634                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21635                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21636                    // Don't care about who enables an app.
21637                    callingPackage = null;
21638                }
21639                pkgSetting.setEnabled(newState, userId, callingPackage);
21640                // pkgSetting.pkg.mSetEnabled = newState;
21641            } else {
21642                // We're dealing with a component level state change
21643                // First, verify that this is a valid class name.
21644                PackageParser.Package pkg = pkgSetting.pkg;
21645                if (pkg == null || !pkg.hasComponentClassName(className)) {
21646                    if (pkg != null &&
21647                            pkg.applicationInfo.targetSdkVersion >=
21648                                    Build.VERSION_CODES.JELLY_BEAN) {
21649                        throw new IllegalArgumentException("Component class " + className
21650                                + " does not exist in " + packageName);
21651                    } else {
21652                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21653                                + className + " does not exist in " + packageName);
21654                    }
21655                }
21656                switch (newState) {
21657                case COMPONENT_ENABLED_STATE_ENABLED:
21658                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21659                        return;
21660                    }
21661                    break;
21662                case COMPONENT_ENABLED_STATE_DISABLED:
21663                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21664                        return;
21665                    }
21666                    break;
21667                case COMPONENT_ENABLED_STATE_DEFAULT:
21668                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21669                        return;
21670                    }
21671                    break;
21672                default:
21673                    Slog.e(TAG, "Invalid new component state: " + newState);
21674                    return;
21675                }
21676            }
21677            scheduleWritePackageRestrictionsLocked(userId);
21678            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21679            final long callingId = Binder.clearCallingIdentity();
21680            try {
21681                updateInstantAppInstallerLocked(packageName);
21682            } finally {
21683                Binder.restoreCallingIdentity(callingId);
21684            }
21685            components = mPendingBroadcasts.get(userId, packageName);
21686            final boolean newPackage = components == null;
21687            if (newPackage) {
21688                components = new ArrayList<String>();
21689            }
21690            if (!components.contains(componentName)) {
21691                components.add(componentName);
21692            }
21693            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21694                sendNow = true;
21695                // Purge entry from pending broadcast list if another one exists already
21696                // since we are sending one right away.
21697                mPendingBroadcasts.remove(userId, packageName);
21698            } else {
21699                if (newPackage) {
21700                    mPendingBroadcasts.put(userId, packageName, components);
21701                }
21702                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21703                    // Schedule a message
21704                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21705                }
21706            }
21707        }
21708
21709        long callingId = Binder.clearCallingIdentity();
21710        try {
21711            if (sendNow) {
21712                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21713                sendPackageChangedBroadcast(packageName,
21714                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21715            }
21716        } finally {
21717            Binder.restoreCallingIdentity(callingId);
21718        }
21719    }
21720
21721    @Override
21722    public void flushPackageRestrictionsAsUser(int userId) {
21723        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21724            return;
21725        }
21726        if (!sUserManager.exists(userId)) {
21727            return;
21728        }
21729        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21730                false /* checkShell */, "flushPackageRestrictions");
21731        synchronized (mPackages) {
21732            mSettings.writePackageRestrictionsLPr(userId);
21733            mDirtyUsers.remove(userId);
21734            if (mDirtyUsers.isEmpty()) {
21735                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21736            }
21737        }
21738    }
21739
21740    private void sendPackageChangedBroadcast(String packageName,
21741            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21742        if (DEBUG_INSTALL)
21743            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21744                    + componentNames);
21745        Bundle extras = new Bundle(4);
21746        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21747        String nameList[] = new String[componentNames.size()];
21748        componentNames.toArray(nameList);
21749        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21750        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21751        extras.putInt(Intent.EXTRA_UID, packageUid);
21752        // If this is not reporting a change of the overall package, then only send it
21753        // to registered receivers.  We don't want to launch a swath of apps for every
21754        // little component state change.
21755        final int flags = !componentNames.contains(packageName)
21756                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21757        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21758                new int[] {UserHandle.getUserId(packageUid)});
21759    }
21760
21761    @Override
21762    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21763        if (!sUserManager.exists(userId)) return;
21764        final int callingUid = Binder.getCallingUid();
21765        if (getInstantAppPackageName(callingUid) != null) {
21766            return;
21767        }
21768        final int permission = mContext.checkCallingOrSelfPermission(
21769                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21770        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21771        enforceCrossUserPermission(callingUid, userId,
21772                true /* requireFullPermission */, true /* checkShell */, "stop package");
21773        // writer
21774        synchronized (mPackages) {
21775            final PackageSetting ps = mSettings.mPackages.get(packageName);
21776            if (!filterAppAccessLPr(ps, callingUid, userId)
21777                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21778                            allowedByPermission, callingUid, userId)) {
21779                scheduleWritePackageRestrictionsLocked(userId);
21780            }
21781        }
21782    }
21783
21784    @Override
21785    public String getInstallerPackageName(String packageName) {
21786        final int callingUid = Binder.getCallingUid();
21787        if (getInstantAppPackageName(callingUid) != null) {
21788            return null;
21789        }
21790        // reader
21791        synchronized (mPackages) {
21792            final PackageSetting ps = mSettings.mPackages.get(packageName);
21793            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21794                return null;
21795            }
21796            return mSettings.getInstallerPackageNameLPr(packageName);
21797        }
21798    }
21799
21800    public boolean isOrphaned(String packageName) {
21801        // reader
21802        synchronized (mPackages) {
21803            return mSettings.isOrphaned(packageName);
21804        }
21805    }
21806
21807    @Override
21808    public int getApplicationEnabledSetting(String packageName, int userId) {
21809        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21810        int callingUid = Binder.getCallingUid();
21811        enforceCrossUserPermission(callingUid, userId,
21812                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21813        // reader
21814        synchronized (mPackages) {
21815            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21816                return COMPONENT_ENABLED_STATE_DISABLED;
21817            }
21818            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21819        }
21820    }
21821
21822    @Override
21823    public int getComponentEnabledSetting(ComponentName component, int userId) {
21824        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21825        int callingUid = Binder.getCallingUid();
21826        enforceCrossUserPermission(callingUid, userId,
21827                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21828        synchronized (mPackages) {
21829            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21830                    component, TYPE_UNKNOWN, userId)) {
21831                return COMPONENT_ENABLED_STATE_DISABLED;
21832            }
21833            return mSettings.getComponentEnabledSettingLPr(component, userId);
21834        }
21835    }
21836
21837    @Override
21838    public void enterSafeMode() {
21839        enforceSystemOrRoot("Only the system can request entering safe mode");
21840
21841        if (!mSystemReady) {
21842            mSafeMode = true;
21843        }
21844    }
21845
21846    @Override
21847    public void systemReady() {
21848        enforceSystemOrRoot("Only the system can claim the system is ready");
21849
21850        mSystemReady = true;
21851        final ContentResolver resolver = mContext.getContentResolver();
21852        ContentObserver co = new ContentObserver(mHandler) {
21853            @Override
21854            public void onChange(boolean selfChange) {
21855                mEphemeralAppsDisabled =
21856                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21857                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21858            }
21859        };
21860        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21861                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21862                false, co, UserHandle.USER_SYSTEM);
21863        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21864                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21865        co.onChange(true);
21866
21867        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21868        // disabled after already being started.
21869        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21870                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21871
21872        // Read the compatibilty setting when the system is ready.
21873        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21874                mContext.getContentResolver(),
21875                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21876        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21877        if (DEBUG_SETTINGS) {
21878            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21879        }
21880
21881        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21882
21883        synchronized (mPackages) {
21884            // Verify that all of the preferred activity components actually
21885            // exist.  It is possible for applications to be updated and at
21886            // that point remove a previously declared activity component that
21887            // had been set as a preferred activity.  We try to clean this up
21888            // the next time we encounter that preferred activity, but it is
21889            // possible for the user flow to never be able to return to that
21890            // situation so here we do a sanity check to make sure we haven't
21891            // left any junk around.
21892            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21893            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21894                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21895                removed.clear();
21896                for (PreferredActivity pa : pir.filterSet()) {
21897                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21898                        removed.add(pa);
21899                    }
21900                }
21901                if (removed.size() > 0) {
21902                    for (int r=0; r<removed.size(); r++) {
21903                        PreferredActivity pa = removed.get(r);
21904                        Slog.w(TAG, "Removing dangling preferred activity: "
21905                                + pa.mPref.mComponent);
21906                        pir.removeFilter(pa);
21907                    }
21908                    mSettings.writePackageRestrictionsLPr(
21909                            mSettings.mPreferredActivities.keyAt(i));
21910                }
21911            }
21912
21913            for (int userId : UserManagerService.getInstance().getUserIds()) {
21914                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21915                    grantPermissionsUserIds = ArrayUtils.appendInt(
21916                            grantPermissionsUserIds, userId);
21917                }
21918            }
21919        }
21920        sUserManager.systemReady();
21921
21922        // If we upgraded grant all default permissions before kicking off.
21923        for (int userId : grantPermissionsUserIds) {
21924            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21925        }
21926
21927        // If we did not grant default permissions, we preload from this the
21928        // default permission exceptions lazily to ensure we don't hit the
21929        // disk on a new user creation.
21930        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21931            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21932        }
21933
21934        // Kick off any messages waiting for system ready
21935        if (mPostSystemReadyMessages != null) {
21936            for (Message msg : mPostSystemReadyMessages) {
21937                msg.sendToTarget();
21938            }
21939            mPostSystemReadyMessages = null;
21940        }
21941
21942        // Watch for external volumes that come and go over time
21943        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21944        storage.registerListener(mStorageListener);
21945
21946        mInstallerService.systemReady();
21947        mPackageDexOptimizer.systemReady();
21948
21949        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21950                StorageManagerInternal.class);
21951        StorageManagerInternal.addExternalStoragePolicy(
21952                new StorageManagerInternal.ExternalStorageMountPolicy() {
21953            @Override
21954            public int getMountMode(int uid, String packageName) {
21955                if (Process.isIsolated(uid)) {
21956                    return Zygote.MOUNT_EXTERNAL_NONE;
21957                }
21958                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21959                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21960                }
21961                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21962                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21963                }
21964                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21965                    return Zygote.MOUNT_EXTERNAL_READ;
21966                }
21967                return Zygote.MOUNT_EXTERNAL_WRITE;
21968            }
21969
21970            @Override
21971            public boolean hasExternalStorage(int uid, String packageName) {
21972                return true;
21973            }
21974        });
21975
21976        // Now that we're mostly running, clean up stale users and apps
21977        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21978        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21979
21980        if (mPrivappPermissionsViolations != null) {
21981            Slog.wtf(TAG,"Signature|privileged permissions not in "
21982                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21983            mPrivappPermissionsViolations = null;
21984        }
21985    }
21986
21987    public void waitForAppDataPrepared() {
21988        if (mPrepareAppDataFuture == null) {
21989            return;
21990        }
21991        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21992        mPrepareAppDataFuture = null;
21993    }
21994
21995    @Override
21996    public boolean isSafeMode() {
21997        // allow instant applications
21998        return mSafeMode;
21999    }
22000
22001    @Override
22002    public boolean hasSystemUidErrors() {
22003        // allow instant applications
22004        return mHasSystemUidErrors;
22005    }
22006
22007    static String arrayToString(int[] array) {
22008        StringBuffer buf = new StringBuffer(128);
22009        buf.append('[');
22010        if (array != null) {
22011            for (int i=0; i<array.length; i++) {
22012                if (i > 0) buf.append(", ");
22013                buf.append(array[i]);
22014            }
22015        }
22016        buf.append(']');
22017        return buf.toString();
22018    }
22019
22020    static class DumpState {
22021        public static final int DUMP_LIBS = 1 << 0;
22022        public static final int DUMP_FEATURES = 1 << 1;
22023        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22024        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22025        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22026        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22027        public static final int DUMP_PERMISSIONS = 1 << 6;
22028        public static final int DUMP_PACKAGES = 1 << 7;
22029        public static final int DUMP_SHARED_USERS = 1 << 8;
22030        public static final int DUMP_MESSAGES = 1 << 9;
22031        public static final int DUMP_PROVIDERS = 1 << 10;
22032        public static final int DUMP_VERIFIERS = 1 << 11;
22033        public static final int DUMP_PREFERRED = 1 << 12;
22034        public static final int DUMP_PREFERRED_XML = 1 << 13;
22035        public static final int DUMP_KEYSETS = 1 << 14;
22036        public static final int DUMP_VERSION = 1 << 15;
22037        public static final int DUMP_INSTALLS = 1 << 16;
22038        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22039        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22040        public static final int DUMP_FROZEN = 1 << 19;
22041        public static final int DUMP_DEXOPT = 1 << 20;
22042        public static final int DUMP_COMPILER_STATS = 1 << 21;
22043        public static final int DUMP_CHANGES = 1 << 22;
22044        public static final int DUMP_VOLUMES = 1 << 23;
22045
22046        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22047
22048        private int mTypes;
22049
22050        private int mOptions;
22051
22052        private boolean mTitlePrinted;
22053
22054        private SharedUserSetting mSharedUser;
22055
22056        public boolean isDumping(int type) {
22057            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22058                return true;
22059            }
22060
22061            return (mTypes & type) != 0;
22062        }
22063
22064        public void setDump(int type) {
22065            mTypes |= type;
22066        }
22067
22068        public boolean isOptionEnabled(int option) {
22069            return (mOptions & option) != 0;
22070        }
22071
22072        public void setOptionEnabled(int option) {
22073            mOptions |= option;
22074        }
22075
22076        public boolean onTitlePrinted() {
22077            final boolean printed = mTitlePrinted;
22078            mTitlePrinted = true;
22079            return printed;
22080        }
22081
22082        public boolean getTitlePrinted() {
22083            return mTitlePrinted;
22084        }
22085
22086        public void setTitlePrinted(boolean enabled) {
22087            mTitlePrinted = enabled;
22088        }
22089
22090        public SharedUserSetting getSharedUser() {
22091            return mSharedUser;
22092        }
22093
22094        public void setSharedUser(SharedUserSetting user) {
22095            mSharedUser = user;
22096        }
22097    }
22098
22099    @Override
22100    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22101            FileDescriptor err, String[] args, ShellCallback callback,
22102            ResultReceiver resultReceiver) {
22103        (new PackageManagerShellCommand(this)).exec(
22104                this, in, out, err, args, callback, resultReceiver);
22105    }
22106
22107    @Override
22108    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22109        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22110
22111        DumpState dumpState = new DumpState();
22112        boolean fullPreferred = false;
22113        boolean checkin = false;
22114
22115        String packageName = null;
22116        ArraySet<String> permissionNames = null;
22117
22118        int opti = 0;
22119        while (opti < args.length) {
22120            String opt = args[opti];
22121            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22122                break;
22123            }
22124            opti++;
22125
22126            if ("-a".equals(opt)) {
22127                // Right now we only know how to print all.
22128            } else if ("-h".equals(opt)) {
22129                pw.println("Package manager dump options:");
22130                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22131                pw.println("    --checkin: dump for a checkin");
22132                pw.println("    -f: print details of intent filters");
22133                pw.println("    -h: print this help");
22134                pw.println("  cmd may be one of:");
22135                pw.println("    l[ibraries]: list known shared libraries");
22136                pw.println("    f[eatures]: list device features");
22137                pw.println("    k[eysets]: print known keysets");
22138                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22139                pw.println("    perm[issions]: dump permissions");
22140                pw.println("    permission [name ...]: dump declaration and use of given permission");
22141                pw.println("    pref[erred]: print preferred package settings");
22142                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22143                pw.println("    prov[iders]: dump content providers");
22144                pw.println("    p[ackages]: dump installed packages");
22145                pw.println("    s[hared-users]: dump shared user IDs");
22146                pw.println("    m[essages]: print collected runtime messages");
22147                pw.println("    v[erifiers]: print package verifier info");
22148                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22149                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22150                pw.println("    version: print database version info");
22151                pw.println("    write: write current settings now");
22152                pw.println("    installs: details about install sessions");
22153                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22154                pw.println("    dexopt: dump dexopt state");
22155                pw.println("    compiler-stats: dump compiler statistics");
22156                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22157                pw.println("    <package.name>: info about given package");
22158                return;
22159            } else if ("--checkin".equals(opt)) {
22160                checkin = true;
22161            } else if ("-f".equals(opt)) {
22162                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22163            } else if ("--proto".equals(opt)) {
22164                dumpProto(fd);
22165                return;
22166            } else {
22167                pw.println("Unknown argument: " + opt + "; use -h for help");
22168            }
22169        }
22170
22171        // Is the caller requesting to dump a particular piece of data?
22172        if (opti < args.length) {
22173            String cmd = args[opti];
22174            opti++;
22175            // Is this a package name?
22176            if ("android".equals(cmd) || cmd.contains(".")) {
22177                packageName = cmd;
22178                // When dumping a single package, we always dump all of its
22179                // filter information since the amount of data will be reasonable.
22180                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22181            } else if ("check-permission".equals(cmd)) {
22182                if (opti >= args.length) {
22183                    pw.println("Error: check-permission missing permission argument");
22184                    return;
22185                }
22186                String perm = args[opti];
22187                opti++;
22188                if (opti >= args.length) {
22189                    pw.println("Error: check-permission missing package argument");
22190                    return;
22191                }
22192
22193                String pkg = args[opti];
22194                opti++;
22195                int user = UserHandle.getUserId(Binder.getCallingUid());
22196                if (opti < args.length) {
22197                    try {
22198                        user = Integer.parseInt(args[opti]);
22199                    } catch (NumberFormatException e) {
22200                        pw.println("Error: check-permission user argument is not a number: "
22201                                + args[opti]);
22202                        return;
22203                    }
22204                }
22205
22206                // Normalize package name to handle renamed packages and static libs
22207                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22208
22209                pw.println(checkPermission(perm, pkg, user));
22210                return;
22211            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22212                dumpState.setDump(DumpState.DUMP_LIBS);
22213            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22214                dumpState.setDump(DumpState.DUMP_FEATURES);
22215            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22216                if (opti >= args.length) {
22217                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22218                            | DumpState.DUMP_SERVICE_RESOLVERS
22219                            | DumpState.DUMP_RECEIVER_RESOLVERS
22220                            | DumpState.DUMP_CONTENT_RESOLVERS);
22221                } else {
22222                    while (opti < args.length) {
22223                        String name = args[opti];
22224                        if ("a".equals(name) || "activity".equals(name)) {
22225                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22226                        } else if ("s".equals(name) || "service".equals(name)) {
22227                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22228                        } else if ("r".equals(name) || "receiver".equals(name)) {
22229                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22230                        } else if ("c".equals(name) || "content".equals(name)) {
22231                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22232                        } else {
22233                            pw.println("Error: unknown resolver table type: " + name);
22234                            return;
22235                        }
22236                        opti++;
22237                    }
22238                }
22239            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22240                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22241            } else if ("permission".equals(cmd)) {
22242                if (opti >= args.length) {
22243                    pw.println("Error: permission requires permission name");
22244                    return;
22245                }
22246                permissionNames = new ArraySet<>();
22247                while (opti < args.length) {
22248                    permissionNames.add(args[opti]);
22249                    opti++;
22250                }
22251                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22252                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22253            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22254                dumpState.setDump(DumpState.DUMP_PREFERRED);
22255            } else if ("preferred-xml".equals(cmd)) {
22256                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22257                if (opti < args.length && "--full".equals(args[opti])) {
22258                    fullPreferred = true;
22259                    opti++;
22260                }
22261            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22262                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22263            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22264                dumpState.setDump(DumpState.DUMP_PACKAGES);
22265            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22266                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22267            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22268                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22269            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22270                dumpState.setDump(DumpState.DUMP_MESSAGES);
22271            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22272                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22273            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22274                    || "intent-filter-verifiers".equals(cmd)) {
22275                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22276            } else if ("version".equals(cmd)) {
22277                dumpState.setDump(DumpState.DUMP_VERSION);
22278            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22279                dumpState.setDump(DumpState.DUMP_KEYSETS);
22280            } else if ("installs".equals(cmd)) {
22281                dumpState.setDump(DumpState.DUMP_INSTALLS);
22282            } else if ("frozen".equals(cmd)) {
22283                dumpState.setDump(DumpState.DUMP_FROZEN);
22284            } else if ("volumes".equals(cmd)) {
22285                dumpState.setDump(DumpState.DUMP_VOLUMES);
22286            } else if ("dexopt".equals(cmd)) {
22287                dumpState.setDump(DumpState.DUMP_DEXOPT);
22288            } else if ("compiler-stats".equals(cmd)) {
22289                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22290            } else if ("changes".equals(cmd)) {
22291                dumpState.setDump(DumpState.DUMP_CHANGES);
22292            } else if ("write".equals(cmd)) {
22293                synchronized (mPackages) {
22294                    mSettings.writeLPr();
22295                    pw.println("Settings written.");
22296                    return;
22297                }
22298            }
22299        }
22300
22301        if (checkin) {
22302            pw.println("vers,1");
22303        }
22304
22305        // reader
22306        synchronized (mPackages) {
22307            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22308                if (!checkin) {
22309                    if (dumpState.onTitlePrinted())
22310                        pw.println();
22311                    pw.println("Database versions:");
22312                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22313                }
22314            }
22315
22316            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22317                if (!checkin) {
22318                    if (dumpState.onTitlePrinted())
22319                        pw.println();
22320                    pw.println("Verifiers:");
22321                    pw.print("  Required: ");
22322                    pw.print(mRequiredVerifierPackage);
22323                    pw.print(" (uid=");
22324                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22325                            UserHandle.USER_SYSTEM));
22326                    pw.println(")");
22327                } else if (mRequiredVerifierPackage != null) {
22328                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22329                    pw.print(",");
22330                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22331                            UserHandle.USER_SYSTEM));
22332                }
22333            }
22334
22335            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22336                    packageName == null) {
22337                if (mIntentFilterVerifierComponent != null) {
22338                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22339                    if (!checkin) {
22340                        if (dumpState.onTitlePrinted())
22341                            pw.println();
22342                        pw.println("Intent Filter Verifier:");
22343                        pw.print("  Using: ");
22344                        pw.print(verifierPackageName);
22345                        pw.print(" (uid=");
22346                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22347                                UserHandle.USER_SYSTEM));
22348                        pw.println(")");
22349                    } else if (verifierPackageName != null) {
22350                        pw.print("ifv,"); pw.print(verifierPackageName);
22351                        pw.print(",");
22352                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22353                                UserHandle.USER_SYSTEM));
22354                    }
22355                } else {
22356                    pw.println();
22357                    pw.println("No Intent Filter Verifier available!");
22358                }
22359            }
22360
22361            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22362                boolean printedHeader = false;
22363                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22364                while (it.hasNext()) {
22365                    String libName = it.next();
22366                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22367                    if (versionedLib == null) {
22368                        continue;
22369                    }
22370                    final int versionCount = versionedLib.size();
22371                    for (int i = 0; i < versionCount; i++) {
22372                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22373                        if (!checkin) {
22374                            if (!printedHeader) {
22375                                if (dumpState.onTitlePrinted())
22376                                    pw.println();
22377                                pw.println("Libraries:");
22378                                printedHeader = true;
22379                            }
22380                            pw.print("  ");
22381                        } else {
22382                            pw.print("lib,");
22383                        }
22384                        pw.print(libEntry.info.getName());
22385                        if (libEntry.info.isStatic()) {
22386                            pw.print(" version=" + libEntry.info.getVersion());
22387                        }
22388                        if (!checkin) {
22389                            pw.print(" -> ");
22390                        }
22391                        if (libEntry.path != null) {
22392                            pw.print(" (jar) ");
22393                            pw.print(libEntry.path);
22394                        } else {
22395                            pw.print(" (apk) ");
22396                            pw.print(libEntry.apk);
22397                        }
22398                        pw.println();
22399                    }
22400                }
22401            }
22402
22403            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22404                if (dumpState.onTitlePrinted())
22405                    pw.println();
22406                if (!checkin) {
22407                    pw.println("Features:");
22408                }
22409
22410                synchronized (mAvailableFeatures) {
22411                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22412                        if (checkin) {
22413                            pw.print("feat,");
22414                            pw.print(feat.name);
22415                            pw.print(",");
22416                            pw.println(feat.version);
22417                        } else {
22418                            pw.print("  ");
22419                            pw.print(feat.name);
22420                            if (feat.version > 0) {
22421                                pw.print(" version=");
22422                                pw.print(feat.version);
22423                            }
22424                            pw.println();
22425                        }
22426                    }
22427                }
22428            }
22429
22430            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22431                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22432                        : "Activity Resolver Table:", "  ", packageName,
22433                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22434                    dumpState.setTitlePrinted(true);
22435                }
22436            }
22437            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22438                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22439                        : "Receiver Resolver Table:", "  ", packageName,
22440                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22441                    dumpState.setTitlePrinted(true);
22442                }
22443            }
22444            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22445                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22446                        : "Service Resolver Table:", "  ", packageName,
22447                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22448                    dumpState.setTitlePrinted(true);
22449                }
22450            }
22451            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22452                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22453                        : "Provider Resolver Table:", "  ", packageName,
22454                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22455                    dumpState.setTitlePrinted(true);
22456                }
22457            }
22458
22459            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22460                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22461                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22462                    int user = mSettings.mPreferredActivities.keyAt(i);
22463                    if (pir.dump(pw,
22464                            dumpState.getTitlePrinted()
22465                                ? "\nPreferred Activities User " + user + ":"
22466                                : "Preferred Activities User " + user + ":", "  ",
22467                            packageName, true, false)) {
22468                        dumpState.setTitlePrinted(true);
22469                    }
22470                }
22471            }
22472
22473            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22474                pw.flush();
22475                FileOutputStream fout = new FileOutputStream(fd);
22476                BufferedOutputStream str = new BufferedOutputStream(fout);
22477                XmlSerializer serializer = new FastXmlSerializer();
22478                try {
22479                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22480                    serializer.startDocument(null, true);
22481                    serializer.setFeature(
22482                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22483                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22484                    serializer.endDocument();
22485                    serializer.flush();
22486                } catch (IllegalArgumentException e) {
22487                    pw.println("Failed writing: " + e);
22488                } catch (IllegalStateException e) {
22489                    pw.println("Failed writing: " + e);
22490                } catch (IOException e) {
22491                    pw.println("Failed writing: " + e);
22492                }
22493            }
22494
22495            if (!checkin
22496                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22497                    && packageName == null) {
22498                pw.println();
22499                int count = mSettings.mPackages.size();
22500                if (count == 0) {
22501                    pw.println("No applications!");
22502                    pw.println();
22503                } else {
22504                    final String prefix = "  ";
22505                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22506                    if (allPackageSettings.size() == 0) {
22507                        pw.println("No domain preferred apps!");
22508                        pw.println();
22509                    } else {
22510                        pw.println("App verification status:");
22511                        pw.println();
22512                        count = 0;
22513                        for (PackageSetting ps : allPackageSettings) {
22514                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22515                            if (ivi == null || ivi.getPackageName() == null) continue;
22516                            pw.println(prefix + "Package: " + ivi.getPackageName());
22517                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22518                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22519                            pw.println();
22520                            count++;
22521                        }
22522                        if (count == 0) {
22523                            pw.println(prefix + "No app verification established.");
22524                            pw.println();
22525                        }
22526                        for (int userId : sUserManager.getUserIds()) {
22527                            pw.println("App linkages for user " + userId + ":");
22528                            pw.println();
22529                            count = 0;
22530                            for (PackageSetting ps : allPackageSettings) {
22531                                final long status = ps.getDomainVerificationStatusForUser(userId);
22532                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22533                                        && !DEBUG_DOMAIN_VERIFICATION) {
22534                                    continue;
22535                                }
22536                                pw.println(prefix + "Package: " + ps.name);
22537                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22538                                String statusStr = IntentFilterVerificationInfo.
22539                                        getStatusStringFromValue(status);
22540                                pw.println(prefix + "Status:  " + statusStr);
22541                                pw.println();
22542                                count++;
22543                            }
22544                            if (count == 0) {
22545                                pw.println(prefix + "No configured app linkages.");
22546                                pw.println();
22547                            }
22548                        }
22549                    }
22550                }
22551            }
22552
22553            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22554                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22555                if (packageName == null && permissionNames == null) {
22556                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22557                        if (iperm == 0) {
22558                            if (dumpState.onTitlePrinted())
22559                                pw.println();
22560                            pw.println("AppOp Permissions:");
22561                        }
22562                        pw.print("  AppOp Permission ");
22563                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22564                        pw.println(":");
22565                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22566                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22567                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22568                        }
22569                    }
22570                }
22571            }
22572
22573            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22574                boolean printedSomething = false;
22575                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22576                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22577                        continue;
22578                    }
22579                    if (!printedSomething) {
22580                        if (dumpState.onTitlePrinted())
22581                            pw.println();
22582                        pw.println("Registered ContentProviders:");
22583                        printedSomething = true;
22584                    }
22585                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22586                    pw.print("    "); pw.println(p.toString());
22587                }
22588                printedSomething = false;
22589                for (Map.Entry<String, PackageParser.Provider> entry :
22590                        mProvidersByAuthority.entrySet()) {
22591                    PackageParser.Provider p = entry.getValue();
22592                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22593                        continue;
22594                    }
22595                    if (!printedSomething) {
22596                        if (dumpState.onTitlePrinted())
22597                            pw.println();
22598                        pw.println("ContentProvider Authorities:");
22599                        printedSomething = true;
22600                    }
22601                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22602                    pw.print("    "); pw.println(p.toString());
22603                    if (p.info != null && p.info.applicationInfo != null) {
22604                        final String appInfo = p.info.applicationInfo.toString();
22605                        pw.print("      applicationInfo="); pw.println(appInfo);
22606                    }
22607                }
22608            }
22609
22610            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22611                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22612            }
22613
22614            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22615                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22616            }
22617
22618            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22619                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22620            }
22621
22622            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22623                if (dumpState.onTitlePrinted()) pw.println();
22624                pw.println("Package Changes:");
22625                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22626                final int K = mChangedPackages.size();
22627                for (int i = 0; i < K; i++) {
22628                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22629                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22630                    final int N = changes.size();
22631                    if (N == 0) {
22632                        pw.print("    "); pw.println("No packages changed");
22633                    } else {
22634                        for (int j = 0; j < N; j++) {
22635                            final String pkgName = changes.valueAt(j);
22636                            final int sequenceNumber = changes.keyAt(j);
22637                            pw.print("    ");
22638                            pw.print("seq=");
22639                            pw.print(sequenceNumber);
22640                            pw.print(", package=");
22641                            pw.println(pkgName);
22642                        }
22643                    }
22644                }
22645            }
22646
22647            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22648                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22649            }
22650
22651            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22652                // XXX should handle packageName != null by dumping only install data that
22653                // the given package is involved with.
22654                if (dumpState.onTitlePrinted()) pw.println();
22655
22656                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22657                ipw.println();
22658                ipw.println("Frozen packages:");
22659                ipw.increaseIndent();
22660                if (mFrozenPackages.size() == 0) {
22661                    ipw.println("(none)");
22662                } else {
22663                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22664                        ipw.println(mFrozenPackages.valueAt(i));
22665                    }
22666                }
22667                ipw.decreaseIndent();
22668            }
22669
22670            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22671                if (dumpState.onTitlePrinted()) pw.println();
22672
22673                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22674                ipw.println();
22675                ipw.println("Loaded volumes:");
22676                ipw.increaseIndent();
22677                if (mLoadedVolumes.size() == 0) {
22678                    ipw.println("(none)");
22679                } else {
22680                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22681                        ipw.println(mLoadedVolumes.valueAt(i));
22682                    }
22683                }
22684                ipw.decreaseIndent();
22685            }
22686
22687            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22688                if (dumpState.onTitlePrinted()) pw.println();
22689                dumpDexoptStateLPr(pw, packageName);
22690            }
22691
22692            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22693                if (dumpState.onTitlePrinted()) pw.println();
22694                dumpCompilerStatsLPr(pw, packageName);
22695            }
22696
22697            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22698                if (dumpState.onTitlePrinted()) pw.println();
22699                mSettings.dumpReadMessagesLPr(pw, dumpState);
22700
22701                pw.println();
22702                pw.println("Package warning messages:");
22703                BufferedReader in = null;
22704                String line = null;
22705                try {
22706                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22707                    while ((line = in.readLine()) != null) {
22708                        if (line.contains("ignored: updated version")) continue;
22709                        pw.println(line);
22710                    }
22711                } catch (IOException ignored) {
22712                } finally {
22713                    IoUtils.closeQuietly(in);
22714                }
22715            }
22716
22717            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22718                BufferedReader in = null;
22719                String line = null;
22720                try {
22721                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22722                    while ((line = in.readLine()) != null) {
22723                        if (line.contains("ignored: updated version")) continue;
22724                        pw.print("msg,");
22725                        pw.println(line);
22726                    }
22727                } catch (IOException ignored) {
22728                } finally {
22729                    IoUtils.closeQuietly(in);
22730                }
22731            }
22732        }
22733
22734        // PackageInstaller should be called outside of mPackages lock
22735        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22736            // XXX should handle packageName != null by dumping only install data that
22737            // the given package is involved with.
22738            if (dumpState.onTitlePrinted()) pw.println();
22739            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22740        }
22741    }
22742
22743    private void dumpProto(FileDescriptor fd) {
22744        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22745
22746        synchronized (mPackages) {
22747            final long requiredVerifierPackageToken =
22748                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22749            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22750            proto.write(
22751                    PackageServiceDumpProto.PackageShortProto.UID,
22752                    getPackageUid(
22753                            mRequiredVerifierPackage,
22754                            MATCH_DEBUG_TRIAGED_MISSING,
22755                            UserHandle.USER_SYSTEM));
22756            proto.end(requiredVerifierPackageToken);
22757
22758            if (mIntentFilterVerifierComponent != null) {
22759                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22760                final long verifierPackageToken =
22761                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22762                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22763                proto.write(
22764                        PackageServiceDumpProto.PackageShortProto.UID,
22765                        getPackageUid(
22766                                verifierPackageName,
22767                                MATCH_DEBUG_TRIAGED_MISSING,
22768                                UserHandle.USER_SYSTEM));
22769                proto.end(verifierPackageToken);
22770            }
22771
22772            dumpSharedLibrariesProto(proto);
22773            dumpFeaturesProto(proto);
22774            mSettings.dumpPackagesProto(proto);
22775            mSettings.dumpSharedUsersProto(proto);
22776            dumpMessagesProto(proto);
22777        }
22778        proto.flush();
22779    }
22780
22781    private void dumpMessagesProto(ProtoOutputStream proto) {
22782        BufferedReader in = null;
22783        String line = null;
22784        try {
22785            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22786            while ((line = in.readLine()) != null) {
22787                if (line.contains("ignored: updated version")) continue;
22788                proto.write(PackageServiceDumpProto.MESSAGES, line);
22789            }
22790        } catch (IOException ignored) {
22791        } finally {
22792            IoUtils.closeQuietly(in);
22793        }
22794    }
22795
22796    private void dumpFeaturesProto(ProtoOutputStream proto) {
22797        synchronized (mAvailableFeatures) {
22798            final int count = mAvailableFeatures.size();
22799            for (int i = 0; i < count; i++) {
22800                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22801                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22802                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22803                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22804                proto.end(featureToken);
22805            }
22806        }
22807    }
22808
22809    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22810        final int count = mSharedLibraries.size();
22811        for (int i = 0; i < count; i++) {
22812            final String libName = mSharedLibraries.keyAt(i);
22813            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22814            if (versionedLib == null) {
22815                continue;
22816            }
22817            final int versionCount = versionedLib.size();
22818            for (int j = 0; j < versionCount; j++) {
22819                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22820                final long sharedLibraryToken =
22821                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22822                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22823                final boolean isJar = (libEntry.path != null);
22824                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22825                if (isJar) {
22826                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22827                } else {
22828                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22829                }
22830                proto.end(sharedLibraryToken);
22831            }
22832        }
22833    }
22834
22835    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22836        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22837        ipw.println();
22838        ipw.println("Dexopt state:");
22839        ipw.increaseIndent();
22840        Collection<PackageParser.Package> packages = null;
22841        if (packageName != null) {
22842            PackageParser.Package targetPackage = mPackages.get(packageName);
22843            if (targetPackage != null) {
22844                packages = Collections.singletonList(targetPackage);
22845            } else {
22846                ipw.println("Unable to find package: " + packageName);
22847                return;
22848            }
22849        } else {
22850            packages = mPackages.values();
22851        }
22852
22853        for (PackageParser.Package pkg : packages) {
22854            ipw.println("[" + pkg.packageName + "]");
22855            ipw.increaseIndent();
22856            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22857            ipw.decreaseIndent();
22858        }
22859    }
22860
22861    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22862        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22863        ipw.println();
22864        ipw.println("Compiler stats:");
22865        ipw.increaseIndent();
22866        Collection<PackageParser.Package> packages = null;
22867        if (packageName != null) {
22868            PackageParser.Package targetPackage = mPackages.get(packageName);
22869            if (targetPackage != null) {
22870                packages = Collections.singletonList(targetPackage);
22871            } else {
22872                ipw.println("Unable to find package: " + packageName);
22873                return;
22874            }
22875        } else {
22876            packages = mPackages.values();
22877        }
22878
22879        for (PackageParser.Package pkg : packages) {
22880            ipw.println("[" + pkg.packageName + "]");
22881            ipw.increaseIndent();
22882
22883            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22884            if (stats == null) {
22885                ipw.println("(No recorded stats)");
22886            } else {
22887                stats.dump(ipw);
22888            }
22889            ipw.decreaseIndent();
22890        }
22891    }
22892
22893    private String dumpDomainString(String packageName) {
22894        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22895                .getList();
22896        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22897
22898        ArraySet<String> result = new ArraySet<>();
22899        if (iviList.size() > 0) {
22900            for (IntentFilterVerificationInfo ivi : iviList) {
22901                for (String host : ivi.getDomains()) {
22902                    result.add(host);
22903                }
22904            }
22905        }
22906        if (filters != null && filters.size() > 0) {
22907            for (IntentFilter filter : filters) {
22908                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22909                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22910                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22911                    result.addAll(filter.getHostsList());
22912                }
22913            }
22914        }
22915
22916        StringBuilder sb = new StringBuilder(result.size() * 16);
22917        for (String domain : result) {
22918            if (sb.length() > 0) sb.append(" ");
22919            sb.append(domain);
22920        }
22921        return sb.toString();
22922    }
22923
22924    // ------- apps on sdcard specific code -------
22925    static final boolean DEBUG_SD_INSTALL = false;
22926
22927    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22928
22929    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22930
22931    private boolean mMediaMounted = false;
22932
22933    static String getEncryptKey() {
22934        try {
22935            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22936                    SD_ENCRYPTION_KEYSTORE_NAME);
22937            if (sdEncKey == null) {
22938                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22939                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22940                if (sdEncKey == null) {
22941                    Slog.e(TAG, "Failed to create encryption keys");
22942                    return null;
22943                }
22944            }
22945            return sdEncKey;
22946        } catch (NoSuchAlgorithmException nsae) {
22947            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22948            return null;
22949        } catch (IOException ioe) {
22950            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22951            return null;
22952        }
22953    }
22954
22955    /*
22956     * Update media status on PackageManager.
22957     */
22958    @Override
22959    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22960        enforceSystemOrRoot("Media status can only be updated by the system");
22961        // reader; this apparently protects mMediaMounted, but should probably
22962        // be a different lock in that case.
22963        synchronized (mPackages) {
22964            Log.i(TAG, "Updating external media status from "
22965                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22966                    + (mediaStatus ? "mounted" : "unmounted"));
22967            if (DEBUG_SD_INSTALL)
22968                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22969                        + ", mMediaMounted=" + mMediaMounted);
22970            if (mediaStatus == mMediaMounted) {
22971                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22972                        : 0, -1);
22973                mHandler.sendMessage(msg);
22974                return;
22975            }
22976            mMediaMounted = mediaStatus;
22977        }
22978        // Queue up an async operation since the package installation may take a
22979        // little while.
22980        mHandler.post(new Runnable() {
22981            public void run() {
22982                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22983            }
22984        });
22985    }
22986
22987    /**
22988     * Called by StorageManagerService when the initial ASECs to scan are available.
22989     * Should block until all the ASEC containers are finished being scanned.
22990     */
22991    public void scanAvailableAsecs() {
22992        updateExternalMediaStatusInner(true, false, false);
22993    }
22994
22995    /*
22996     * Collect information of applications on external media, map them against
22997     * existing containers and update information based on current mount status.
22998     * Please note that we always have to report status if reportStatus has been
22999     * set to true especially when unloading packages.
23000     */
23001    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23002            boolean externalStorage) {
23003        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23004        int[] uidArr = EmptyArray.INT;
23005
23006        final String[] list = PackageHelper.getSecureContainerList();
23007        if (ArrayUtils.isEmpty(list)) {
23008            Log.i(TAG, "No secure containers found");
23009        } else {
23010            // Process list of secure containers and categorize them
23011            // as active or stale based on their package internal state.
23012
23013            // reader
23014            synchronized (mPackages) {
23015                for (String cid : list) {
23016                    // Leave stages untouched for now; installer service owns them
23017                    if (PackageInstallerService.isStageName(cid)) continue;
23018
23019                    if (DEBUG_SD_INSTALL)
23020                        Log.i(TAG, "Processing container " + cid);
23021                    String pkgName = getAsecPackageName(cid);
23022                    if (pkgName == null) {
23023                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23024                        continue;
23025                    }
23026                    if (DEBUG_SD_INSTALL)
23027                        Log.i(TAG, "Looking for pkg : " + pkgName);
23028
23029                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23030                    if (ps == null) {
23031                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23032                        continue;
23033                    }
23034
23035                    /*
23036                     * Skip packages that are not external if we're unmounting
23037                     * external storage.
23038                     */
23039                    if (externalStorage && !isMounted && !isExternal(ps)) {
23040                        continue;
23041                    }
23042
23043                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23044                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23045                    // The package status is changed only if the code path
23046                    // matches between settings and the container id.
23047                    if (ps.codePathString != null
23048                            && ps.codePathString.startsWith(args.getCodePath())) {
23049                        if (DEBUG_SD_INSTALL) {
23050                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23051                                    + " at code path: " + ps.codePathString);
23052                        }
23053
23054                        // We do have a valid package installed on sdcard
23055                        processCids.put(args, ps.codePathString);
23056                        final int uid = ps.appId;
23057                        if (uid != -1) {
23058                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23059                        }
23060                    } else {
23061                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23062                                + ps.codePathString);
23063                    }
23064                }
23065            }
23066
23067            Arrays.sort(uidArr);
23068        }
23069
23070        // Process packages with valid entries.
23071        if (isMounted) {
23072            if (DEBUG_SD_INSTALL)
23073                Log.i(TAG, "Loading packages");
23074            loadMediaPackages(processCids, uidArr, externalStorage);
23075            startCleaningPackages();
23076            mInstallerService.onSecureContainersAvailable();
23077        } else {
23078            if (DEBUG_SD_INSTALL)
23079                Log.i(TAG, "Unloading packages");
23080            unloadMediaPackages(processCids, uidArr, reportStatus);
23081        }
23082    }
23083
23084    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23085            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23086        final int size = infos.size();
23087        final String[] packageNames = new String[size];
23088        final int[] packageUids = new int[size];
23089        for (int i = 0; i < size; i++) {
23090            final ApplicationInfo info = infos.get(i);
23091            packageNames[i] = info.packageName;
23092            packageUids[i] = info.uid;
23093        }
23094        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23095                finishedReceiver);
23096    }
23097
23098    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23099            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23100        sendResourcesChangedBroadcast(mediaStatus, replacing,
23101                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23102    }
23103
23104    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23105            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23106        int size = pkgList.length;
23107        if (size > 0) {
23108            // Send broadcasts here
23109            Bundle extras = new Bundle();
23110            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23111            if (uidArr != null) {
23112                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23113            }
23114            if (replacing) {
23115                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23116            }
23117            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23118                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23119            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23120        }
23121    }
23122
23123   /*
23124     * Look at potentially valid container ids from processCids If package
23125     * information doesn't match the one on record or package scanning fails,
23126     * the cid is added to list of removeCids. We currently don't delete stale
23127     * containers.
23128     */
23129    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23130            boolean externalStorage) {
23131        ArrayList<String> pkgList = new ArrayList<String>();
23132        Set<AsecInstallArgs> keys = processCids.keySet();
23133
23134        for (AsecInstallArgs args : keys) {
23135            String codePath = processCids.get(args);
23136            if (DEBUG_SD_INSTALL)
23137                Log.i(TAG, "Loading container : " + args.cid);
23138            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23139            try {
23140                // Make sure there are no container errors first.
23141                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23142                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23143                            + " when installing from sdcard");
23144                    continue;
23145                }
23146                // Check code path here.
23147                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23148                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23149                            + " does not match one in settings " + codePath);
23150                    continue;
23151                }
23152                // Parse package
23153                int parseFlags = mDefParseFlags;
23154                if (args.isExternalAsec()) {
23155                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23156                }
23157                if (args.isFwdLocked()) {
23158                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23159                }
23160
23161                synchronized (mInstallLock) {
23162                    PackageParser.Package pkg = null;
23163                    try {
23164                        // Sadly we don't know the package name yet to freeze it
23165                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23166                                SCAN_IGNORE_FROZEN, 0, null);
23167                    } catch (PackageManagerException e) {
23168                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23169                    }
23170                    // Scan the package
23171                    if (pkg != null) {
23172                        /*
23173                         * TODO why is the lock being held? doPostInstall is
23174                         * called in other places without the lock. This needs
23175                         * to be straightened out.
23176                         */
23177                        // writer
23178                        synchronized (mPackages) {
23179                            retCode = PackageManager.INSTALL_SUCCEEDED;
23180                            pkgList.add(pkg.packageName);
23181                            // Post process args
23182                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23183                                    pkg.applicationInfo.uid);
23184                        }
23185                    } else {
23186                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23187                    }
23188                }
23189
23190            } finally {
23191                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23192                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23193                }
23194            }
23195        }
23196        // writer
23197        synchronized (mPackages) {
23198            // If the platform SDK has changed since the last time we booted,
23199            // we need to re-grant app permission to catch any new ones that
23200            // appear. This is really a hack, and means that apps can in some
23201            // cases get permissions that the user didn't initially explicitly
23202            // allow... it would be nice to have some better way to handle
23203            // this situation.
23204            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23205                    : mSettings.getInternalVersion();
23206            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23207                    : StorageManager.UUID_PRIVATE_INTERNAL;
23208
23209            int updateFlags = UPDATE_PERMISSIONS_ALL;
23210            if (ver.sdkVersion != mSdkVersion) {
23211                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23212                        + mSdkVersion + "; regranting permissions for external");
23213                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23214            }
23215            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23216
23217            // Yay, everything is now upgraded
23218            ver.forceCurrent();
23219
23220            // can downgrade to reader
23221            // Persist settings
23222            mSettings.writeLPr();
23223        }
23224        // Send a broadcast to let everyone know we are done processing
23225        if (pkgList.size() > 0) {
23226            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23227        }
23228    }
23229
23230   /*
23231     * Utility method to unload a list of specified containers
23232     */
23233    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23234        // Just unmount all valid containers.
23235        for (AsecInstallArgs arg : cidArgs) {
23236            synchronized (mInstallLock) {
23237                arg.doPostDeleteLI(false);
23238           }
23239       }
23240   }
23241
23242    /*
23243     * Unload packages mounted on external media. This involves deleting package
23244     * data from internal structures, sending broadcasts about disabled packages,
23245     * gc'ing to free up references, unmounting all secure containers
23246     * corresponding to packages on external media, and posting a
23247     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23248     * that we always have to post this message if status has been requested no
23249     * matter what.
23250     */
23251    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23252            final boolean reportStatus) {
23253        if (DEBUG_SD_INSTALL)
23254            Log.i(TAG, "unloading media packages");
23255        ArrayList<String> pkgList = new ArrayList<String>();
23256        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23257        final Set<AsecInstallArgs> keys = processCids.keySet();
23258        for (AsecInstallArgs args : keys) {
23259            String pkgName = args.getPackageName();
23260            if (DEBUG_SD_INSTALL)
23261                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23262            // Delete package internally
23263            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23264            synchronized (mInstallLock) {
23265                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23266                final boolean res;
23267                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23268                        "unloadMediaPackages")) {
23269                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23270                            null);
23271                }
23272                if (res) {
23273                    pkgList.add(pkgName);
23274                } else {
23275                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23276                    failedList.add(args);
23277                }
23278            }
23279        }
23280
23281        // reader
23282        synchronized (mPackages) {
23283            // We didn't update the settings after removing each package;
23284            // write them now for all packages.
23285            mSettings.writeLPr();
23286        }
23287
23288        // We have to absolutely send UPDATED_MEDIA_STATUS only
23289        // after confirming that all the receivers processed the ordered
23290        // broadcast when packages get disabled, force a gc to clean things up.
23291        // and unload all the containers.
23292        if (pkgList.size() > 0) {
23293            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23294                    new IIntentReceiver.Stub() {
23295                public void performReceive(Intent intent, int resultCode, String data,
23296                        Bundle extras, boolean ordered, boolean sticky,
23297                        int sendingUser) throws RemoteException {
23298                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23299                            reportStatus ? 1 : 0, 1, keys);
23300                    mHandler.sendMessage(msg);
23301                }
23302            });
23303        } else {
23304            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23305                    keys);
23306            mHandler.sendMessage(msg);
23307        }
23308    }
23309
23310    private void loadPrivatePackages(final VolumeInfo vol) {
23311        mHandler.post(new Runnable() {
23312            @Override
23313            public void run() {
23314                loadPrivatePackagesInner(vol);
23315            }
23316        });
23317    }
23318
23319    private void loadPrivatePackagesInner(VolumeInfo vol) {
23320        final String volumeUuid = vol.fsUuid;
23321        if (TextUtils.isEmpty(volumeUuid)) {
23322            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23323            return;
23324        }
23325
23326        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23327        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23328        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23329
23330        final VersionInfo ver;
23331        final List<PackageSetting> packages;
23332        synchronized (mPackages) {
23333            ver = mSettings.findOrCreateVersion(volumeUuid);
23334            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23335        }
23336
23337        for (PackageSetting ps : packages) {
23338            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23339            synchronized (mInstallLock) {
23340                final PackageParser.Package pkg;
23341                try {
23342                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23343                    loaded.add(pkg.applicationInfo);
23344
23345                } catch (PackageManagerException e) {
23346                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23347                }
23348
23349                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23350                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23351                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23352                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23353                }
23354            }
23355        }
23356
23357        // Reconcile app data for all started/unlocked users
23358        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23359        final UserManager um = mContext.getSystemService(UserManager.class);
23360        UserManagerInternal umInternal = getUserManagerInternal();
23361        for (UserInfo user : um.getUsers()) {
23362            final int flags;
23363            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23364                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23365            } else if (umInternal.isUserRunning(user.id)) {
23366                flags = StorageManager.FLAG_STORAGE_DE;
23367            } else {
23368                continue;
23369            }
23370
23371            try {
23372                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23373                synchronized (mInstallLock) {
23374                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23375                }
23376            } catch (IllegalStateException e) {
23377                // Device was probably ejected, and we'll process that event momentarily
23378                Slog.w(TAG, "Failed to prepare storage: " + e);
23379            }
23380        }
23381
23382        synchronized (mPackages) {
23383            int updateFlags = UPDATE_PERMISSIONS_ALL;
23384            if (ver.sdkVersion != mSdkVersion) {
23385                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23386                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23387                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23388            }
23389            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23390
23391            // Yay, everything is now upgraded
23392            ver.forceCurrent();
23393
23394            mSettings.writeLPr();
23395        }
23396
23397        for (PackageFreezer freezer : freezers) {
23398            freezer.close();
23399        }
23400
23401        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23402        sendResourcesChangedBroadcast(true, false, loaded, null);
23403        mLoadedVolumes.add(vol.getId());
23404    }
23405
23406    private void unloadPrivatePackages(final VolumeInfo vol) {
23407        mHandler.post(new Runnable() {
23408            @Override
23409            public void run() {
23410                unloadPrivatePackagesInner(vol);
23411            }
23412        });
23413    }
23414
23415    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23416        final String volumeUuid = vol.fsUuid;
23417        if (TextUtils.isEmpty(volumeUuid)) {
23418            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23419            return;
23420        }
23421
23422        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23423        synchronized (mInstallLock) {
23424        synchronized (mPackages) {
23425            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23426            for (PackageSetting ps : packages) {
23427                if (ps.pkg == null) continue;
23428
23429                final ApplicationInfo info = ps.pkg.applicationInfo;
23430                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23431                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23432
23433                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23434                        "unloadPrivatePackagesInner")) {
23435                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23436                            false, null)) {
23437                        unloaded.add(info);
23438                    } else {
23439                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23440                    }
23441                }
23442
23443                // Try very hard to release any references to this package
23444                // so we don't risk the system server being killed due to
23445                // open FDs
23446                AttributeCache.instance().removePackage(ps.name);
23447            }
23448
23449            mSettings.writeLPr();
23450        }
23451        }
23452
23453        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23454        sendResourcesChangedBroadcast(false, false, unloaded, null);
23455        mLoadedVolumes.remove(vol.getId());
23456
23457        // Try very hard to release any references to this path so we don't risk
23458        // the system server being killed due to open FDs
23459        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23460
23461        for (int i = 0; i < 3; i++) {
23462            System.gc();
23463            System.runFinalization();
23464        }
23465    }
23466
23467    private void assertPackageKnown(String volumeUuid, String packageName)
23468            throws PackageManagerException {
23469        synchronized (mPackages) {
23470            // Normalize package name to handle renamed packages
23471            packageName = normalizePackageNameLPr(packageName);
23472
23473            final PackageSetting ps = mSettings.mPackages.get(packageName);
23474            if (ps == null) {
23475                throw new PackageManagerException("Package " + packageName + " is unknown");
23476            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23477                throw new PackageManagerException(
23478                        "Package " + packageName + " found on unknown volume " + volumeUuid
23479                                + "; expected volume " + ps.volumeUuid);
23480            }
23481        }
23482    }
23483
23484    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23485            throws PackageManagerException {
23486        synchronized (mPackages) {
23487            // Normalize package name to handle renamed packages
23488            packageName = normalizePackageNameLPr(packageName);
23489
23490            final PackageSetting ps = mSettings.mPackages.get(packageName);
23491            if (ps == null) {
23492                throw new PackageManagerException("Package " + packageName + " is unknown");
23493            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23494                throw new PackageManagerException(
23495                        "Package " + packageName + " found on unknown volume " + volumeUuid
23496                                + "; expected volume " + ps.volumeUuid);
23497            } else if (!ps.getInstalled(userId)) {
23498                throw new PackageManagerException(
23499                        "Package " + packageName + " not installed for user " + userId);
23500            }
23501        }
23502    }
23503
23504    private List<String> collectAbsoluteCodePaths() {
23505        synchronized (mPackages) {
23506            List<String> codePaths = new ArrayList<>();
23507            final int packageCount = mSettings.mPackages.size();
23508            for (int i = 0; i < packageCount; i++) {
23509                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23510                codePaths.add(ps.codePath.getAbsolutePath());
23511            }
23512            return codePaths;
23513        }
23514    }
23515
23516    /**
23517     * Examine all apps present on given mounted volume, and destroy apps that
23518     * aren't expected, either due to uninstallation or reinstallation on
23519     * another volume.
23520     */
23521    private void reconcileApps(String volumeUuid) {
23522        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23523        List<File> filesToDelete = null;
23524
23525        final File[] files = FileUtils.listFilesOrEmpty(
23526                Environment.getDataAppDirectory(volumeUuid));
23527        for (File file : files) {
23528            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23529                    && !PackageInstallerService.isStageName(file.getName());
23530            if (!isPackage) {
23531                // Ignore entries which are not packages
23532                continue;
23533            }
23534
23535            String absolutePath = file.getAbsolutePath();
23536
23537            boolean pathValid = false;
23538            final int absoluteCodePathCount = absoluteCodePaths.size();
23539            for (int i = 0; i < absoluteCodePathCount; i++) {
23540                String absoluteCodePath = absoluteCodePaths.get(i);
23541                if (absolutePath.startsWith(absoluteCodePath)) {
23542                    pathValid = true;
23543                    break;
23544                }
23545            }
23546
23547            if (!pathValid) {
23548                if (filesToDelete == null) {
23549                    filesToDelete = new ArrayList<>();
23550                }
23551                filesToDelete.add(file);
23552            }
23553        }
23554
23555        if (filesToDelete != null) {
23556            final int fileToDeleteCount = filesToDelete.size();
23557            for (int i = 0; i < fileToDeleteCount; i++) {
23558                File fileToDelete = filesToDelete.get(i);
23559                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23560                synchronized (mInstallLock) {
23561                    removeCodePathLI(fileToDelete);
23562                }
23563            }
23564        }
23565    }
23566
23567    /**
23568     * Reconcile all app data for the given user.
23569     * <p>
23570     * Verifies that directories exist and that ownership and labeling is
23571     * correct for all installed apps on all mounted volumes.
23572     */
23573    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23574        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23575        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23576            final String volumeUuid = vol.getFsUuid();
23577            synchronized (mInstallLock) {
23578                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23579            }
23580        }
23581    }
23582
23583    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23584            boolean migrateAppData) {
23585        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23586    }
23587
23588    /**
23589     * Reconcile all app data on given mounted volume.
23590     * <p>
23591     * Destroys app data that isn't expected, either due to uninstallation or
23592     * reinstallation on another volume.
23593     * <p>
23594     * Verifies that directories exist and that ownership and labeling is
23595     * correct for all installed apps.
23596     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23597     */
23598    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23599            boolean migrateAppData, boolean onlyCoreApps) {
23600        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23601                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23602        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23603
23604        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23605        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23606
23607        // First look for stale data that doesn't belong, and check if things
23608        // have changed since we did our last restorecon
23609        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23610            if (StorageManager.isFileEncryptedNativeOrEmulated()
23611                    && !StorageManager.isUserKeyUnlocked(userId)) {
23612                throw new RuntimeException(
23613                        "Yikes, someone asked us to reconcile CE storage while " + userId
23614                                + " was still locked; this would have caused massive data loss!");
23615            }
23616
23617            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23618            for (File file : files) {
23619                final String packageName = file.getName();
23620                try {
23621                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23622                } catch (PackageManagerException e) {
23623                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23624                    try {
23625                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23626                                StorageManager.FLAG_STORAGE_CE, 0);
23627                    } catch (InstallerException e2) {
23628                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23629                    }
23630                }
23631            }
23632        }
23633        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23634            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23635            for (File file : files) {
23636                final String packageName = file.getName();
23637                try {
23638                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23639                } catch (PackageManagerException e) {
23640                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23641                    try {
23642                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23643                                StorageManager.FLAG_STORAGE_DE, 0);
23644                    } catch (InstallerException e2) {
23645                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23646                    }
23647                }
23648            }
23649        }
23650
23651        // Ensure that data directories are ready to roll for all packages
23652        // installed for this volume and user
23653        final List<PackageSetting> packages;
23654        synchronized (mPackages) {
23655            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23656        }
23657        int preparedCount = 0;
23658        for (PackageSetting ps : packages) {
23659            final String packageName = ps.name;
23660            if (ps.pkg == null) {
23661                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23662                // TODO: might be due to legacy ASEC apps; we should circle back
23663                // and reconcile again once they're scanned
23664                continue;
23665            }
23666            // Skip non-core apps if requested
23667            if (onlyCoreApps && !ps.pkg.coreApp) {
23668                result.add(packageName);
23669                continue;
23670            }
23671
23672            if (ps.getInstalled(userId)) {
23673                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23674                preparedCount++;
23675            }
23676        }
23677
23678        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23679        return result;
23680    }
23681
23682    /**
23683     * Prepare app data for the given app just after it was installed or
23684     * upgraded. This method carefully only touches users that it's installed
23685     * for, and it forces a restorecon to handle any seinfo changes.
23686     * <p>
23687     * Verifies that directories exist and that ownership and labeling is
23688     * correct for all installed apps. If there is an ownership mismatch, it
23689     * will try recovering system apps by wiping data; third-party app data is
23690     * left intact.
23691     * <p>
23692     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23693     */
23694    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23695        final PackageSetting ps;
23696        synchronized (mPackages) {
23697            ps = mSettings.mPackages.get(pkg.packageName);
23698            mSettings.writeKernelMappingLPr(ps);
23699        }
23700
23701        final UserManager um = mContext.getSystemService(UserManager.class);
23702        UserManagerInternal umInternal = getUserManagerInternal();
23703        for (UserInfo user : um.getUsers()) {
23704            final int flags;
23705            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23706                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23707            } else if (umInternal.isUserRunning(user.id)) {
23708                flags = StorageManager.FLAG_STORAGE_DE;
23709            } else {
23710                continue;
23711            }
23712
23713            if (ps.getInstalled(user.id)) {
23714                // TODO: when user data is locked, mark that we're still dirty
23715                prepareAppDataLIF(pkg, user.id, flags);
23716            }
23717        }
23718    }
23719
23720    /**
23721     * Prepare app data for the given app.
23722     * <p>
23723     * Verifies that directories exist and that ownership and labeling is
23724     * correct for all installed apps. If there is an ownership mismatch, this
23725     * will try recovering system apps by wiping data; third-party app data is
23726     * left intact.
23727     */
23728    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23729        if (pkg == null) {
23730            Slog.wtf(TAG, "Package was null!", new Throwable());
23731            return;
23732        }
23733        prepareAppDataLeafLIF(pkg, userId, flags);
23734        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23735        for (int i = 0; i < childCount; i++) {
23736            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23737        }
23738    }
23739
23740    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23741            boolean maybeMigrateAppData) {
23742        prepareAppDataLIF(pkg, userId, flags);
23743
23744        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23745            // We may have just shuffled around app data directories, so
23746            // prepare them one more time
23747            prepareAppDataLIF(pkg, userId, flags);
23748        }
23749    }
23750
23751    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23752        if (DEBUG_APP_DATA) {
23753            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23754                    + Integer.toHexString(flags));
23755        }
23756
23757        final String volumeUuid = pkg.volumeUuid;
23758        final String packageName = pkg.packageName;
23759        final ApplicationInfo app = pkg.applicationInfo;
23760        final int appId = UserHandle.getAppId(app.uid);
23761
23762        Preconditions.checkNotNull(app.seInfo);
23763
23764        long ceDataInode = -1;
23765        try {
23766            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23767                    appId, app.seInfo, app.targetSdkVersion);
23768        } catch (InstallerException e) {
23769            if (app.isSystemApp()) {
23770                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23771                        + ", but trying to recover: " + e);
23772                destroyAppDataLeafLIF(pkg, userId, flags);
23773                try {
23774                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23775                            appId, app.seInfo, app.targetSdkVersion);
23776                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23777                } catch (InstallerException e2) {
23778                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23779                }
23780            } else {
23781                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23782            }
23783        }
23784
23785        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23786            // TODO: mark this structure as dirty so we persist it!
23787            synchronized (mPackages) {
23788                final PackageSetting ps = mSettings.mPackages.get(packageName);
23789                if (ps != null) {
23790                    ps.setCeDataInode(ceDataInode, userId);
23791                }
23792            }
23793        }
23794
23795        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23796    }
23797
23798    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23799        if (pkg == null) {
23800            Slog.wtf(TAG, "Package was null!", new Throwable());
23801            return;
23802        }
23803        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23804        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23805        for (int i = 0; i < childCount; i++) {
23806            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23807        }
23808    }
23809
23810    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23811        final String volumeUuid = pkg.volumeUuid;
23812        final String packageName = pkg.packageName;
23813        final ApplicationInfo app = pkg.applicationInfo;
23814
23815        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23816            // Create a native library symlink only if we have native libraries
23817            // and if the native libraries are 32 bit libraries. We do not provide
23818            // this symlink for 64 bit libraries.
23819            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23820                final String nativeLibPath = app.nativeLibraryDir;
23821                try {
23822                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23823                            nativeLibPath, userId);
23824                } catch (InstallerException e) {
23825                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23826                }
23827            }
23828        }
23829    }
23830
23831    /**
23832     * For system apps on non-FBE devices, this method migrates any existing
23833     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23834     * requested by the app.
23835     */
23836    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23837        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23838                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23839            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23840                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23841            try {
23842                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23843                        storageTarget);
23844            } catch (InstallerException e) {
23845                logCriticalInfo(Log.WARN,
23846                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23847            }
23848            return true;
23849        } else {
23850            return false;
23851        }
23852    }
23853
23854    public PackageFreezer freezePackage(String packageName, String killReason) {
23855        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23856    }
23857
23858    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23859        return new PackageFreezer(packageName, userId, killReason);
23860    }
23861
23862    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23863            String killReason) {
23864        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23865    }
23866
23867    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23868            String killReason) {
23869        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23870            return new PackageFreezer();
23871        } else {
23872            return freezePackage(packageName, userId, killReason);
23873        }
23874    }
23875
23876    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23877            String killReason) {
23878        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23879    }
23880
23881    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23882            String killReason) {
23883        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23884            return new PackageFreezer();
23885        } else {
23886            return freezePackage(packageName, userId, killReason);
23887        }
23888    }
23889
23890    /**
23891     * Class that freezes and kills the given package upon creation, and
23892     * unfreezes it upon closing. This is typically used when doing surgery on
23893     * app code/data to prevent the app from running while you're working.
23894     */
23895    private class PackageFreezer implements AutoCloseable {
23896        private final String mPackageName;
23897        private final PackageFreezer[] mChildren;
23898
23899        private final boolean mWeFroze;
23900
23901        private final AtomicBoolean mClosed = new AtomicBoolean();
23902        private final CloseGuard mCloseGuard = CloseGuard.get();
23903
23904        /**
23905         * Create and return a stub freezer that doesn't actually do anything,
23906         * typically used when someone requested
23907         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23908         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23909         */
23910        public PackageFreezer() {
23911            mPackageName = null;
23912            mChildren = null;
23913            mWeFroze = false;
23914            mCloseGuard.open("close");
23915        }
23916
23917        public PackageFreezer(String packageName, int userId, String killReason) {
23918            synchronized (mPackages) {
23919                mPackageName = packageName;
23920                mWeFroze = mFrozenPackages.add(mPackageName);
23921
23922                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23923                if (ps != null) {
23924                    killApplication(ps.name, ps.appId, userId, killReason);
23925                }
23926
23927                final PackageParser.Package p = mPackages.get(packageName);
23928                if (p != null && p.childPackages != null) {
23929                    final int N = p.childPackages.size();
23930                    mChildren = new PackageFreezer[N];
23931                    for (int i = 0; i < N; i++) {
23932                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23933                                userId, killReason);
23934                    }
23935                } else {
23936                    mChildren = null;
23937                }
23938            }
23939            mCloseGuard.open("close");
23940        }
23941
23942        @Override
23943        protected void finalize() throws Throwable {
23944            try {
23945                if (mCloseGuard != null) {
23946                    mCloseGuard.warnIfOpen();
23947                }
23948
23949                close();
23950            } finally {
23951                super.finalize();
23952            }
23953        }
23954
23955        @Override
23956        public void close() {
23957            mCloseGuard.close();
23958            if (mClosed.compareAndSet(false, true)) {
23959                synchronized (mPackages) {
23960                    if (mWeFroze) {
23961                        mFrozenPackages.remove(mPackageName);
23962                    }
23963
23964                    if (mChildren != null) {
23965                        for (PackageFreezer freezer : mChildren) {
23966                            freezer.close();
23967                        }
23968                    }
23969                }
23970            }
23971        }
23972    }
23973
23974    /**
23975     * Verify that given package is currently frozen.
23976     */
23977    private void checkPackageFrozen(String packageName) {
23978        synchronized (mPackages) {
23979            if (!mFrozenPackages.contains(packageName)) {
23980                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23981            }
23982        }
23983    }
23984
23985    @Override
23986    public int movePackage(final String packageName, final String volumeUuid) {
23987        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23988
23989        final int callingUid = Binder.getCallingUid();
23990        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23991        final int moveId = mNextMoveId.getAndIncrement();
23992        mHandler.post(new Runnable() {
23993            @Override
23994            public void run() {
23995                try {
23996                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23997                } catch (PackageManagerException e) {
23998                    Slog.w(TAG, "Failed to move " + packageName, e);
23999                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24000                }
24001            }
24002        });
24003        return moveId;
24004    }
24005
24006    private void movePackageInternal(final String packageName, final String volumeUuid,
24007            final int moveId, final int callingUid, UserHandle user)
24008                    throws PackageManagerException {
24009        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24010        final PackageManager pm = mContext.getPackageManager();
24011
24012        final boolean currentAsec;
24013        final String currentVolumeUuid;
24014        final File codeFile;
24015        final String installerPackageName;
24016        final String packageAbiOverride;
24017        final int appId;
24018        final String seinfo;
24019        final String label;
24020        final int targetSdkVersion;
24021        final PackageFreezer freezer;
24022        final int[] installedUserIds;
24023
24024        // reader
24025        synchronized (mPackages) {
24026            final PackageParser.Package pkg = mPackages.get(packageName);
24027            final PackageSetting ps = mSettings.mPackages.get(packageName);
24028            if (pkg == null
24029                    || ps == null
24030                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24031                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24032            }
24033            if (pkg.applicationInfo.isSystemApp()) {
24034                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24035                        "Cannot move system application");
24036            }
24037
24038            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24039            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24040                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24041            if (isInternalStorage && !allow3rdPartyOnInternal) {
24042                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24043                        "3rd party apps are not allowed on internal storage");
24044            }
24045
24046            if (pkg.applicationInfo.isExternalAsec()) {
24047                currentAsec = true;
24048                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24049            } else if (pkg.applicationInfo.isForwardLocked()) {
24050                currentAsec = true;
24051                currentVolumeUuid = "forward_locked";
24052            } else {
24053                currentAsec = false;
24054                currentVolumeUuid = ps.volumeUuid;
24055
24056                final File probe = new File(pkg.codePath);
24057                final File probeOat = new File(probe, "oat");
24058                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24059                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24060                            "Move only supported for modern cluster style installs");
24061                }
24062            }
24063
24064            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24065                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24066                        "Package already moved to " + volumeUuid);
24067            }
24068            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24069                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24070                        "Device admin cannot be moved");
24071            }
24072
24073            if (mFrozenPackages.contains(packageName)) {
24074                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24075                        "Failed to move already frozen package");
24076            }
24077
24078            codeFile = new File(pkg.codePath);
24079            installerPackageName = ps.installerPackageName;
24080            packageAbiOverride = ps.cpuAbiOverrideString;
24081            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24082            seinfo = pkg.applicationInfo.seInfo;
24083            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24084            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24085            freezer = freezePackage(packageName, "movePackageInternal");
24086            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24087        }
24088
24089        final Bundle extras = new Bundle();
24090        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24091        extras.putString(Intent.EXTRA_TITLE, label);
24092        mMoveCallbacks.notifyCreated(moveId, extras);
24093
24094        int installFlags;
24095        final boolean moveCompleteApp;
24096        final File measurePath;
24097
24098        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24099            installFlags = INSTALL_INTERNAL;
24100            moveCompleteApp = !currentAsec;
24101            measurePath = Environment.getDataAppDirectory(volumeUuid);
24102        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24103            installFlags = INSTALL_EXTERNAL;
24104            moveCompleteApp = false;
24105            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24106        } else {
24107            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24108            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24109                    || !volume.isMountedWritable()) {
24110                freezer.close();
24111                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24112                        "Move location not mounted private volume");
24113            }
24114
24115            Preconditions.checkState(!currentAsec);
24116
24117            installFlags = INSTALL_INTERNAL;
24118            moveCompleteApp = true;
24119            measurePath = Environment.getDataAppDirectory(volumeUuid);
24120        }
24121
24122        // If we're moving app data around, we need all the users unlocked
24123        if (moveCompleteApp) {
24124            for (int userId : installedUserIds) {
24125                if (StorageManager.isFileEncryptedNativeOrEmulated()
24126                        && !StorageManager.isUserKeyUnlocked(userId)) {
24127                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24128                            "User " + userId + " must be unlocked");
24129                }
24130            }
24131        }
24132
24133        final PackageStats stats = new PackageStats(null, -1);
24134        synchronized (mInstaller) {
24135            for (int userId : installedUserIds) {
24136                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24137                    freezer.close();
24138                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24139                            "Failed to measure package size");
24140                }
24141            }
24142        }
24143
24144        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24145                + stats.dataSize);
24146
24147        final long startFreeBytes = measurePath.getUsableSpace();
24148        final long sizeBytes;
24149        if (moveCompleteApp) {
24150            sizeBytes = stats.codeSize + stats.dataSize;
24151        } else {
24152            sizeBytes = stats.codeSize;
24153        }
24154
24155        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24156            freezer.close();
24157            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24158                    "Not enough free space to move");
24159        }
24160
24161        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24162
24163        final CountDownLatch installedLatch = new CountDownLatch(1);
24164        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24165            @Override
24166            public void onUserActionRequired(Intent intent) throws RemoteException {
24167                throw new IllegalStateException();
24168            }
24169
24170            @Override
24171            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24172                    Bundle extras) throws RemoteException {
24173                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24174                        + PackageManager.installStatusToString(returnCode, msg));
24175
24176                installedLatch.countDown();
24177                freezer.close();
24178
24179                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24180                switch (status) {
24181                    case PackageInstaller.STATUS_SUCCESS:
24182                        mMoveCallbacks.notifyStatusChanged(moveId,
24183                                PackageManager.MOVE_SUCCEEDED);
24184                        break;
24185                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24186                        mMoveCallbacks.notifyStatusChanged(moveId,
24187                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24188                        break;
24189                    default:
24190                        mMoveCallbacks.notifyStatusChanged(moveId,
24191                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24192                        break;
24193                }
24194            }
24195        };
24196
24197        final MoveInfo move;
24198        if (moveCompleteApp) {
24199            // Kick off a thread to report progress estimates
24200            new Thread() {
24201                @Override
24202                public void run() {
24203                    while (true) {
24204                        try {
24205                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24206                                break;
24207                            }
24208                        } catch (InterruptedException ignored) {
24209                        }
24210
24211                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24212                        final int progress = 10 + (int) MathUtils.constrain(
24213                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24214                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24215                    }
24216                }
24217            }.start();
24218
24219            final String dataAppName = codeFile.getName();
24220            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24221                    dataAppName, appId, seinfo, targetSdkVersion);
24222        } else {
24223            move = null;
24224        }
24225
24226        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24227
24228        final Message msg = mHandler.obtainMessage(INIT_COPY);
24229        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24230        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24231                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24232                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24233                PackageManager.INSTALL_REASON_UNKNOWN);
24234        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24235        msg.obj = params;
24236
24237        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24238                System.identityHashCode(msg.obj));
24239        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24240                System.identityHashCode(msg.obj));
24241
24242        mHandler.sendMessage(msg);
24243    }
24244
24245    @Override
24246    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24247        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24248
24249        final int realMoveId = mNextMoveId.getAndIncrement();
24250        final Bundle extras = new Bundle();
24251        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24252        mMoveCallbacks.notifyCreated(realMoveId, extras);
24253
24254        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24255            @Override
24256            public void onCreated(int moveId, Bundle extras) {
24257                // Ignored
24258            }
24259
24260            @Override
24261            public void onStatusChanged(int moveId, int status, long estMillis) {
24262                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24263            }
24264        };
24265
24266        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24267        storage.setPrimaryStorageUuid(volumeUuid, callback);
24268        return realMoveId;
24269    }
24270
24271    @Override
24272    public int getMoveStatus(int moveId) {
24273        mContext.enforceCallingOrSelfPermission(
24274                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24275        return mMoveCallbacks.mLastStatus.get(moveId);
24276    }
24277
24278    @Override
24279    public void registerMoveCallback(IPackageMoveObserver callback) {
24280        mContext.enforceCallingOrSelfPermission(
24281                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24282        mMoveCallbacks.register(callback);
24283    }
24284
24285    @Override
24286    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24287        mContext.enforceCallingOrSelfPermission(
24288                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24289        mMoveCallbacks.unregister(callback);
24290    }
24291
24292    @Override
24293    public boolean setInstallLocation(int loc) {
24294        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24295                null);
24296        if (getInstallLocation() == loc) {
24297            return true;
24298        }
24299        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24300                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24301            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24302                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24303            return true;
24304        }
24305        return false;
24306   }
24307
24308    @Override
24309    public int getInstallLocation() {
24310        // allow instant app access
24311        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24312                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24313                PackageHelper.APP_INSTALL_AUTO);
24314    }
24315
24316    /** Called by UserManagerService */
24317    void cleanUpUser(UserManagerService userManager, int userHandle) {
24318        synchronized (mPackages) {
24319            mDirtyUsers.remove(userHandle);
24320            mUserNeedsBadging.delete(userHandle);
24321            mSettings.removeUserLPw(userHandle);
24322            mPendingBroadcasts.remove(userHandle);
24323            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24324            removeUnusedPackagesLPw(userManager, userHandle);
24325        }
24326    }
24327
24328    /**
24329     * We're removing userHandle and would like to remove any downloaded packages
24330     * that are no longer in use by any other user.
24331     * @param userHandle the user being removed
24332     */
24333    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24334        final boolean DEBUG_CLEAN_APKS = false;
24335        int [] users = userManager.getUserIds();
24336        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24337        while (psit.hasNext()) {
24338            PackageSetting ps = psit.next();
24339            if (ps.pkg == null) {
24340                continue;
24341            }
24342            final String packageName = ps.pkg.packageName;
24343            // Skip over if system app
24344            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24345                continue;
24346            }
24347            if (DEBUG_CLEAN_APKS) {
24348                Slog.i(TAG, "Checking package " + packageName);
24349            }
24350            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24351            if (keep) {
24352                if (DEBUG_CLEAN_APKS) {
24353                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24354                }
24355            } else {
24356                for (int i = 0; i < users.length; i++) {
24357                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24358                        keep = true;
24359                        if (DEBUG_CLEAN_APKS) {
24360                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24361                                    + users[i]);
24362                        }
24363                        break;
24364                    }
24365                }
24366            }
24367            if (!keep) {
24368                if (DEBUG_CLEAN_APKS) {
24369                    Slog.i(TAG, "  Removing package " + packageName);
24370                }
24371                mHandler.post(new Runnable() {
24372                    public void run() {
24373                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24374                                userHandle, 0);
24375                    } //end run
24376                });
24377            }
24378        }
24379    }
24380
24381    /** Called by UserManagerService */
24382    void createNewUser(int userId, String[] disallowedPackages) {
24383        synchronized (mInstallLock) {
24384            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24385        }
24386        synchronized (mPackages) {
24387            scheduleWritePackageRestrictionsLocked(userId);
24388            scheduleWritePackageListLocked(userId);
24389            applyFactoryDefaultBrowserLPw(userId);
24390            primeDomainVerificationsLPw(userId);
24391        }
24392    }
24393
24394    void onNewUserCreated(final int userId) {
24395        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24396        // If permission review for legacy apps is required, we represent
24397        // dagerous permissions for such apps as always granted runtime
24398        // permissions to keep per user flag state whether review is needed.
24399        // Hence, if a new user is added we have to propagate dangerous
24400        // permission grants for these legacy apps.
24401        if (mPermissionReviewRequired) {
24402            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24403                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24404        }
24405    }
24406
24407    @Override
24408    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24409        mContext.enforceCallingOrSelfPermission(
24410                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24411                "Only package verification agents can read the verifier device identity");
24412
24413        synchronized (mPackages) {
24414            return mSettings.getVerifierDeviceIdentityLPw();
24415        }
24416    }
24417
24418    @Override
24419    public void setPermissionEnforced(String permission, boolean enforced) {
24420        // TODO: Now that we no longer change GID for storage, this should to away.
24421        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24422                "setPermissionEnforced");
24423        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24424            synchronized (mPackages) {
24425                if (mSettings.mReadExternalStorageEnforced == null
24426                        || mSettings.mReadExternalStorageEnforced != enforced) {
24427                    mSettings.mReadExternalStorageEnforced = enforced;
24428                    mSettings.writeLPr();
24429                }
24430            }
24431            // kill any non-foreground processes so we restart them and
24432            // grant/revoke the GID.
24433            final IActivityManager am = ActivityManager.getService();
24434            if (am != null) {
24435                final long token = Binder.clearCallingIdentity();
24436                try {
24437                    am.killProcessesBelowForeground("setPermissionEnforcement");
24438                } catch (RemoteException e) {
24439                } finally {
24440                    Binder.restoreCallingIdentity(token);
24441                }
24442            }
24443        } else {
24444            throw new IllegalArgumentException("No selective enforcement for " + permission);
24445        }
24446    }
24447
24448    @Override
24449    @Deprecated
24450    public boolean isPermissionEnforced(String permission) {
24451        // allow instant applications
24452        return true;
24453    }
24454
24455    @Override
24456    public boolean isStorageLow() {
24457        // allow instant applications
24458        final long token = Binder.clearCallingIdentity();
24459        try {
24460            final DeviceStorageMonitorInternal
24461                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24462            if (dsm != null) {
24463                return dsm.isMemoryLow();
24464            } else {
24465                return false;
24466            }
24467        } finally {
24468            Binder.restoreCallingIdentity(token);
24469        }
24470    }
24471
24472    @Override
24473    public IPackageInstaller getPackageInstaller() {
24474        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24475            return null;
24476        }
24477        return mInstallerService;
24478    }
24479
24480    private boolean userNeedsBadging(int userId) {
24481        int index = mUserNeedsBadging.indexOfKey(userId);
24482        if (index < 0) {
24483            final UserInfo userInfo;
24484            final long token = Binder.clearCallingIdentity();
24485            try {
24486                userInfo = sUserManager.getUserInfo(userId);
24487            } finally {
24488                Binder.restoreCallingIdentity(token);
24489            }
24490            final boolean b;
24491            if (userInfo != null && userInfo.isManagedProfile()) {
24492                b = true;
24493            } else {
24494                b = false;
24495            }
24496            mUserNeedsBadging.put(userId, b);
24497            return b;
24498        }
24499        return mUserNeedsBadging.valueAt(index);
24500    }
24501
24502    @Override
24503    public KeySet getKeySetByAlias(String packageName, String alias) {
24504        if (packageName == null || alias == null) {
24505            return null;
24506        }
24507        synchronized(mPackages) {
24508            final PackageParser.Package pkg = mPackages.get(packageName);
24509            if (pkg == null) {
24510                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24511                throw new IllegalArgumentException("Unknown package: " + packageName);
24512            }
24513            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24514            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24515                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24516                throw new IllegalArgumentException("Unknown package: " + packageName);
24517            }
24518            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24519            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24520        }
24521    }
24522
24523    @Override
24524    public KeySet getSigningKeySet(String packageName) {
24525        if (packageName == null) {
24526            return null;
24527        }
24528        synchronized(mPackages) {
24529            final int callingUid = Binder.getCallingUid();
24530            final int callingUserId = UserHandle.getUserId(callingUid);
24531            final PackageParser.Package pkg = mPackages.get(packageName);
24532            if (pkg == null) {
24533                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24534                throw new IllegalArgumentException("Unknown package: " + packageName);
24535            }
24536            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24537            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24538                // filter and pretend the package doesn't exist
24539                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24540                        + ", uid:" + callingUid);
24541                throw new IllegalArgumentException("Unknown package: " + packageName);
24542            }
24543            if (pkg.applicationInfo.uid != callingUid
24544                    && Process.SYSTEM_UID != callingUid) {
24545                throw new SecurityException("May not access signing KeySet of other apps.");
24546            }
24547            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24548            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24549        }
24550    }
24551
24552    @Override
24553    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24554        final int callingUid = Binder.getCallingUid();
24555        if (getInstantAppPackageName(callingUid) != null) {
24556            return false;
24557        }
24558        if (packageName == null || ks == null) {
24559            return false;
24560        }
24561        synchronized(mPackages) {
24562            final PackageParser.Package pkg = mPackages.get(packageName);
24563            if (pkg == null
24564                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24565                            UserHandle.getUserId(callingUid))) {
24566                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24567                throw new IllegalArgumentException("Unknown package: " + packageName);
24568            }
24569            IBinder ksh = ks.getToken();
24570            if (ksh instanceof KeySetHandle) {
24571                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24572                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24573            }
24574            return false;
24575        }
24576    }
24577
24578    @Override
24579    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24580        final int callingUid = Binder.getCallingUid();
24581        if (getInstantAppPackageName(callingUid) != null) {
24582            return false;
24583        }
24584        if (packageName == null || ks == null) {
24585            return false;
24586        }
24587        synchronized(mPackages) {
24588            final PackageParser.Package pkg = mPackages.get(packageName);
24589            if (pkg == null
24590                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24591                            UserHandle.getUserId(callingUid))) {
24592                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24593                throw new IllegalArgumentException("Unknown package: " + packageName);
24594            }
24595            IBinder ksh = ks.getToken();
24596            if (ksh instanceof KeySetHandle) {
24597                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24598                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24599            }
24600            return false;
24601        }
24602    }
24603
24604    private void deletePackageIfUnusedLPr(final String packageName) {
24605        PackageSetting ps = mSettings.mPackages.get(packageName);
24606        if (ps == null) {
24607            return;
24608        }
24609        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24610            // TODO Implement atomic delete if package is unused
24611            // It is currently possible that the package will be deleted even if it is installed
24612            // after this method returns.
24613            mHandler.post(new Runnable() {
24614                public void run() {
24615                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24616                            0, PackageManager.DELETE_ALL_USERS);
24617                }
24618            });
24619        }
24620    }
24621
24622    /**
24623     * Check and throw if the given before/after packages would be considered a
24624     * downgrade.
24625     */
24626    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24627            throws PackageManagerException {
24628        if (after.versionCode < before.mVersionCode) {
24629            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24630                    "Update version code " + after.versionCode + " is older than current "
24631                    + before.mVersionCode);
24632        } else if (after.versionCode == before.mVersionCode) {
24633            if (after.baseRevisionCode < before.baseRevisionCode) {
24634                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24635                        "Update base revision code " + after.baseRevisionCode
24636                        + " is older than current " + before.baseRevisionCode);
24637            }
24638
24639            if (!ArrayUtils.isEmpty(after.splitNames)) {
24640                for (int i = 0; i < after.splitNames.length; i++) {
24641                    final String splitName = after.splitNames[i];
24642                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24643                    if (j != -1) {
24644                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24645                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24646                                    "Update split " + splitName + " revision code "
24647                                    + after.splitRevisionCodes[i] + " is older than current "
24648                                    + before.splitRevisionCodes[j]);
24649                        }
24650                    }
24651                }
24652            }
24653        }
24654    }
24655
24656    private static class MoveCallbacks extends Handler {
24657        private static final int MSG_CREATED = 1;
24658        private static final int MSG_STATUS_CHANGED = 2;
24659
24660        private final RemoteCallbackList<IPackageMoveObserver>
24661                mCallbacks = new RemoteCallbackList<>();
24662
24663        private final SparseIntArray mLastStatus = new SparseIntArray();
24664
24665        public MoveCallbacks(Looper looper) {
24666            super(looper);
24667        }
24668
24669        public void register(IPackageMoveObserver callback) {
24670            mCallbacks.register(callback);
24671        }
24672
24673        public void unregister(IPackageMoveObserver callback) {
24674            mCallbacks.unregister(callback);
24675        }
24676
24677        @Override
24678        public void handleMessage(Message msg) {
24679            final SomeArgs args = (SomeArgs) msg.obj;
24680            final int n = mCallbacks.beginBroadcast();
24681            for (int i = 0; i < n; i++) {
24682                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24683                try {
24684                    invokeCallback(callback, msg.what, args);
24685                } catch (RemoteException ignored) {
24686                }
24687            }
24688            mCallbacks.finishBroadcast();
24689            args.recycle();
24690        }
24691
24692        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24693                throws RemoteException {
24694            switch (what) {
24695                case MSG_CREATED: {
24696                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24697                    break;
24698                }
24699                case MSG_STATUS_CHANGED: {
24700                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24701                    break;
24702                }
24703            }
24704        }
24705
24706        private void notifyCreated(int moveId, Bundle extras) {
24707            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24708
24709            final SomeArgs args = SomeArgs.obtain();
24710            args.argi1 = moveId;
24711            args.arg2 = extras;
24712            obtainMessage(MSG_CREATED, args).sendToTarget();
24713        }
24714
24715        private void notifyStatusChanged(int moveId, int status) {
24716            notifyStatusChanged(moveId, status, -1);
24717        }
24718
24719        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24720            Slog.v(TAG, "Move " + moveId + " status " + status);
24721
24722            final SomeArgs args = SomeArgs.obtain();
24723            args.argi1 = moveId;
24724            args.argi2 = status;
24725            args.arg3 = estMillis;
24726            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24727
24728            synchronized (mLastStatus) {
24729                mLastStatus.put(moveId, status);
24730            }
24731        }
24732    }
24733
24734    private final static class OnPermissionChangeListeners extends Handler {
24735        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24736
24737        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24738                new RemoteCallbackList<>();
24739
24740        public OnPermissionChangeListeners(Looper looper) {
24741            super(looper);
24742        }
24743
24744        @Override
24745        public void handleMessage(Message msg) {
24746            switch (msg.what) {
24747                case MSG_ON_PERMISSIONS_CHANGED: {
24748                    final int uid = msg.arg1;
24749                    handleOnPermissionsChanged(uid);
24750                } break;
24751            }
24752        }
24753
24754        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24755            mPermissionListeners.register(listener);
24756
24757        }
24758
24759        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24760            mPermissionListeners.unregister(listener);
24761        }
24762
24763        public void onPermissionsChanged(int uid) {
24764            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24765                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24766            }
24767        }
24768
24769        private void handleOnPermissionsChanged(int uid) {
24770            final int count = mPermissionListeners.beginBroadcast();
24771            try {
24772                for (int i = 0; i < count; i++) {
24773                    IOnPermissionsChangeListener callback = mPermissionListeners
24774                            .getBroadcastItem(i);
24775                    try {
24776                        callback.onPermissionsChanged(uid);
24777                    } catch (RemoteException e) {
24778                        Log.e(TAG, "Permission listener is dead", e);
24779                    }
24780                }
24781            } finally {
24782                mPermissionListeners.finishBroadcast();
24783            }
24784        }
24785    }
24786
24787    private class PackageManagerInternalImpl extends PackageManagerInternal {
24788        @Override
24789        public void setLocationPackagesProvider(PackagesProvider provider) {
24790            synchronized (mPackages) {
24791                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24792            }
24793        }
24794
24795        @Override
24796        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24797            synchronized (mPackages) {
24798                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24799            }
24800        }
24801
24802        @Override
24803        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24804            synchronized (mPackages) {
24805                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24806            }
24807        }
24808
24809        @Override
24810        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24811            synchronized (mPackages) {
24812                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24813            }
24814        }
24815
24816        @Override
24817        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24818            synchronized (mPackages) {
24819                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24820            }
24821        }
24822
24823        @Override
24824        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24825            synchronized (mPackages) {
24826                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24827            }
24828        }
24829
24830        @Override
24831        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24832            synchronized (mPackages) {
24833                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24834                        packageName, userId);
24835            }
24836        }
24837
24838        @Override
24839        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24840            synchronized (mPackages) {
24841                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24842                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24843                        packageName, userId);
24844            }
24845        }
24846
24847        @Override
24848        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24849            synchronized (mPackages) {
24850                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24851                        packageName, userId);
24852            }
24853        }
24854
24855        @Override
24856        public void setKeepUninstalledPackages(final List<String> packageList) {
24857            Preconditions.checkNotNull(packageList);
24858            List<String> removedFromList = null;
24859            synchronized (mPackages) {
24860                if (mKeepUninstalledPackages != null) {
24861                    final int packagesCount = mKeepUninstalledPackages.size();
24862                    for (int i = 0; i < packagesCount; i++) {
24863                        String oldPackage = mKeepUninstalledPackages.get(i);
24864                        if (packageList != null && packageList.contains(oldPackage)) {
24865                            continue;
24866                        }
24867                        if (removedFromList == null) {
24868                            removedFromList = new ArrayList<>();
24869                        }
24870                        removedFromList.add(oldPackage);
24871                    }
24872                }
24873                mKeepUninstalledPackages = new ArrayList<>(packageList);
24874                if (removedFromList != null) {
24875                    final int removedCount = removedFromList.size();
24876                    for (int i = 0; i < removedCount; i++) {
24877                        deletePackageIfUnusedLPr(removedFromList.get(i));
24878                    }
24879                }
24880            }
24881        }
24882
24883        @Override
24884        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24885            synchronized (mPackages) {
24886                // If we do not support permission review, done.
24887                if (!mPermissionReviewRequired) {
24888                    return false;
24889                }
24890
24891                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24892                if (packageSetting == null) {
24893                    return false;
24894                }
24895
24896                // Permission review applies only to apps not supporting the new permission model.
24897                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24898                    return false;
24899                }
24900
24901                // Legacy apps have the permission and get user consent on launch.
24902                PermissionsState permissionsState = packageSetting.getPermissionsState();
24903                return permissionsState.isPermissionReviewRequired(userId);
24904            }
24905        }
24906
24907        @Override
24908        public PackageInfo getPackageInfo(
24909                String packageName, int flags, int filterCallingUid, int userId) {
24910            return PackageManagerService.this
24911                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24912                            flags, filterCallingUid, userId);
24913        }
24914
24915        @Override
24916        public ApplicationInfo getApplicationInfo(
24917                String packageName, int flags, int filterCallingUid, int userId) {
24918            return PackageManagerService.this
24919                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24920        }
24921
24922        @Override
24923        public ActivityInfo getActivityInfo(
24924                ComponentName component, int flags, int filterCallingUid, int userId) {
24925            return PackageManagerService.this
24926                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24927        }
24928
24929        @Override
24930        public List<ResolveInfo> queryIntentActivities(
24931                Intent intent, int flags, int filterCallingUid, int userId) {
24932            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24933            return PackageManagerService.this
24934                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24935                            userId, false /*resolveForStart*/);
24936        }
24937
24938        @Override
24939        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24940                int userId) {
24941            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24942        }
24943
24944        @Override
24945        public void setDeviceAndProfileOwnerPackages(
24946                int deviceOwnerUserId, String deviceOwnerPackage,
24947                SparseArray<String> profileOwnerPackages) {
24948            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24949                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24950        }
24951
24952        @Override
24953        public boolean isPackageDataProtected(int userId, String packageName) {
24954            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24955        }
24956
24957        @Override
24958        public boolean isPackageEphemeral(int userId, String packageName) {
24959            synchronized (mPackages) {
24960                final PackageSetting ps = mSettings.mPackages.get(packageName);
24961                return ps != null ? ps.getInstantApp(userId) : false;
24962            }
24963        }
24964
24965        @Override
24966        public boolean wasPackageEverLaunched(String packageName, int userId) {
24967            synchronized (mPackages) {
24968                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24969            }
24970        }
24971
24972        @Override
24973        public void grantRuntimePermission(String packageName, String name, int userId,
24974                boolean overridePolicy) {
24975            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24976                    overridePolicy);
24977        }
24978
24979        @Override
24980        public void revokeRuntimePermission(String packageName, String name, int userId,
24981                boolean overridePolicy) {
24982            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24983                    overridePolicy);
24984        }
24985
24986        @Override
24987        public String getNameForUid(int uid) {
24988            return PackageManagerService.this.getNameForUid(uid);
24989        }
24990
24991        @Override
24992        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24993                Intent origIntent, String resolvedType, String callingPackage,
24994                Bundle verificationBundle, int userId) {
24995            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24996                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24997                    userId);
24998        }
24999
25000        @Override
25001        public void grantEphemeralAccess(int userId, Intent intent,
25002                int targetAppId, int ephemeralAppId) {
25003            synchronized (mPackages) {
25004                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25005                        targetAppId, ephemeralAppId);
25006            }
25007        }
25008
25009        @Override
25010        public boolean isInstantAppInstallerComponent(ComponentName component) {
25011            synchronized (mPackages) {
25012                return mInstantAppInstallerActivity != null
25013                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25014            }
25015        }
25016
25017        @Override
25018        public void pruneInstantApps() {
25019            mInstantAppRegistry.pruneInstantApps();
25020        }
25021
25022        @Override
25023        public String getSetupWizardPackageName() {
25024            return mSetupWizardPackage;
25025        }
25026
25027        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25028            if (policy != null) {
25029                mExternalSourcesPolicy = policy;
25030            }
25031        }
25032
25033        @Override
25034        public boolean isPackagePersistent(String packageName) {
25035            synchronized (mPackages) {
25036                PackageParser.Package pkg = mPackages.get(packageName);
25037                return pkg != null
25038                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25039                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25040                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25041                        : false;
25042            }
25043        }
25044
25045        @Override
25046        public List<PackageInfo> getOverlayPackages(int userId) {
25047            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25048            synchronized (mPackages) {
25049                for (PackageParser.Package p : mPackages.values()) {
25050                    if (p.mOverlayTarget != null) {
25051                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25052                        if (pkg != null) {
25053                            overlayPackages.add(pkg);
25054                        }
25055                    }
25056                }
25057            }
25058            return overlayPackages;
25059        }
25060
25061        @Override
25062        public List<String> getTargetPackageNames(int userId) {
25063            List<String> targetPackages = new ArrayList<>();
25064            synchronized (mPackages) {
25065                for (PackageParser.Package p : mPackages.values()) {
25066                    if (p.mOverlayTarget == null) {
25067                        targetPackages.add(p.packageName);
25068                    }
25069                }
25070            }
25071            return targetPackages;
25072        }
25073
25074        @Override
25075        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25076                @Nullable List<String> overlayPackageNames) {
25077            synchronized (mPackages) {
25078                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25079                    Slog.e(TAG, "failed to find package " + targetPackageName);
25080                    return false;
25081                }
25082                ArrayList<String> overlayPaths = null;
25083                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25084                    final int N = overlayPackageNames.size();
25085                    overlayPaths = new ArrayList<>(N);
25086                    for (int i = 0; i < N; i++) {
25087                        final String packageName = overlayPackageNames.get(i);
25088                        final PackageParser.Package pkg = mPackages.get(packageName);
25089                        if (pkg == null) {
25090                            Slog.e(TAG, "failed to find package " + packageName);
25091                            return false;
25092                        }
25093                        overlayPaths.add(pkg.baseCodePath);
25094                    }
25095                }
25096
25097                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25098                ps.setOverlayPaths(overlayPaths, userId);
25099                return true;
25100            }
25101        }
25102
25103        @Override
25104        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25105                int flags, int userId) {
25106            return resolveIntentInternal(
25107                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25108        }
25109
25110        @Override
25111        public ResolveInfo resolveService(Intent intent, String resolvedType,
25112                int flags, int userId, int callingUid) {
25113            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25114        }
25115
25116        @Override
25117        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25118            synchronized (mPackages) {
25119                mIsolatedOwners.put(isolatedUid, ownerUid);
25120            }
25121        }
25122
25123        @Override
25124        public void removeIsolatedUid(int isolatedUid) {
25125            synchronized (mPackages) {
25126                mIsolatedOwners.delete(isolatedUid);
25127            }
25128        }
25129
25130        @Override
25131        public int getUidTargetSdkVersion(int uid) {
25132            synchronized (mPackages) {
25133                return getUidTargetSdkVersionLockedLPr(uid);
25134            }
25135        }
25136
25137        @Override
25138        public boolean canAccessInstantApps(int callingUid, int userId) {
25139            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25140        }
25141    }
25142
25143    @Override
25144    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25145        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25146        synchronized (mPackages) {
25147            final long identity = Binder.clearCallingIdentity();
25148            try {
25149                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25150                        packageNames, userId);
25151            } finally {
25152                Binder.restoreCallingIdentity(identity);
25153            }
25154        }
25155    }
25156
25157    @Override
25158    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25159        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25160        synchronized (mPackages) {
25161            final long identity = Binder.clearCallingIdentity();
25162            try {
25163                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25164                        packageNames, userId);
25165            } finally {
25166                Binder.restoreCallingIdentity(identity);
25167            }
25168        }
25169    }
25170
25171    private static void enforceSystemOrPhoneCaller(String tag) {
25172        int callingUid = Binder.getCallingUid();
25173        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25174            throw new SecurityException(
25175                    "Cannot call " + tag + " from UID " + callingUid);
25176        }
25177    }
25178
25179    boolean isHistoricalPackageUsageAvailable() {
25180        return mPackageUsage.isHistoricalPackageUsageAvailable();
25181    }
25182
25183    /**
25184     * Return a <b>copy</b> of the collection of packages known to the package manager.
25185     * @return A copy of the values of mPackages.
25186     */
25187    Collection<PackageParser.Package> getPackages() {
25188        synchronized (mPackages) {
25189            return new ArrayList<>(mPackages.values());
25190        }
25191    }
25192
25193    /**
25194     * Logs process start information (including base APK hash) to the security log.
25195     * @hide
25196     */
25197    @Override
25198    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25199            String apkFile, int pid) {
25200        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25201            return;
25202        }
25203        if (!SecurityLog.isLoggingEnabled()) {
25204            return;
25205        }
25206        Bundle data = new Bundle();
25207        data.putLong("startTimestamp", System.currentTimeMillis());
25208        data.putString("processName", processName);
25209        data.putInt("uid", uid);
25210        data.putString("seinfo", seinfo);
25211        data.putString("apkFile", apkFile);
25212        data.putInt("pid", pid);
25213        Message msg = mProcessLoggingHandler.obtainMessage(
25214                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25215        msg.setData(data);
25216        mProcessLoggingHandler.sendMessage(msg);
25217    }
25218
25219    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25220        return mCompilerStats.getPackageStats(pkgName);
25221    }
25222
25223    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25224        return getOrCreateCompilerPackageStats(pkg.packageName);
25225    }
25226
25227    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25228        return mCompilerStats.getOrCreatePackageStats(pkgName);
25229    }
25230
25231    public void deleteCompilerPackageStats(String pkgName) {
25232        mCompilerStats.deletePackageStats(pkgName);
25233    }
25234
25235    @Override
25236    public int getInstallReason(String packageName, int userId) {
25237        final int callingUid = Binder.getCallingUid();
25238        enforceCrossUserPermission(callingUid, userId,
25239                true /* requireFullPermission */, false /* checkShell */,
25240                "get install reason");
25241        synchronized (mPackages) {
25242            final PackageSetting ps = mSettings.mPackages.get(packageName);
25243            if (filterAppAccessLPr(ps, callingUid, userId)) {
25244                return PackageManager.INSTALL_REASON_UNKNOWN;
25245            }
25246            if (ps != null) {
25247                return ps.getInstallReason(userId);
25248            }
25249        }
25250        return PackageManager.INSTALL_REASON_UNKNOWN;
25251    }
25252
25253    @Override
25254    public boolean canRequestPackageInstalls(String packageName, int userId) {
25255        return canRequestPackageInstallsInternal(packageName, 0, userId,
25256                true /* throwIfPermNotDeclared*/);
25257    }
25258
25259    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25260            boolean throwIfPermNotDeclared) {
25261        int callingUid = Binder.getCallingUid();
25262        int uid = getPackageUid(packageName, 0, userId);
25263        if (callingUid != uid && callingUid != Process.ROOT_UID
25264                && callingUid != Process.SYSTEM_UID) {
25265            throw new SecurityException(
25266                    "Caller uid " + callingUid + " does not own package " + packageName);
25267        }
25268        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25269        if (info == null) {
25270            return false;
25271        }
25272        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25273            return false;
25274        }
25275        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25276        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25277        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25278            if (throwIfPermNotDeclared) {
25279                throw new SecurityException("Need to declare " + appOpPermission
25280                        + " to call this api");
25281            } else {
25282                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25283                return false;
25284            }
25285        }
25286        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25287            return false;
25288        }
25289        if (mExternalSourcesPolicy != null) {
25290            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25291            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25292                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25293            }
25294        }
25295        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25296    }
25297
25298    @Override
25299    public ComponentName getInstantAppResolverSettingsComponent() {
25300        return mInstantAppResolverSettingsComponent;
25301    }
25302
25303    @Override
25304    public ComponentName getInstantAppInstallerComponent() {
25305        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25306            return null;
25307        }
25308        return mInstantAppInstallerActivity == null
25309                ? null : mInstantAppInstallerActivity.getComponentName();
25310    }
25311
25312    @Override
25313    public String getInstantAppAndroidId(String packageName, int userId) {
25314        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25315                "getInstantAppAndroidId");
25316        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25317                true /* requireFullPermission */, false /* checkShell */,
25318                "getInstantAppAndroidId");
25319        // Make sure the target is an Instant App.
25320        if (!isInstantApp(packageName, userId)) {
25321            return null;
25322        }
25323        synchronized (mPackages) {
25324            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25325        }
25326    }
25327
25328    boolean canHaveOatDir(String packageName) {
25329        synchronized (mPackages) {
25330            PackageParser.Package p = mPackages.get(packageName);
25331            if (p == null) {
25332                return false;
25333            }
25334            return p.canHaveOatDir();
25335        }
25336    }
25337
25338    private String getOatDir(PackageParser.Package pkg) {
25339        if (!pkg.canHaveOatDir()) {
25340            return null;
25341        }
25342        File codePath = new File(pkg.codePath);
25343        if (codePath.isDirectory()) {
25344            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25345        }
25346        return null;
25347    }
25348
25349    void deleteOatArtifactsOfPackage(String packageName) {
25350        final String[] instructionSets;
25351        final List<String> codePaths;
25352        final String oatDir;
25353        final PackageParser.Package pkg;
25354        synchronized (mPackages) {
25355            pkg = mPackages.get(packageName);
25356        }
25357        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25358        codePaths = pkg.getAllCodePaths();
25359        oatDir = getOatDir(pkg);
25360
25361        for (String codePath : codePaths) {
25362            for (String isa : instructionSets) {
25363                try {
25364                    mInstaller.deleteOdex(codePath, isa, oatDir);
25365                } catch (InstallerException e) {
25366                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25367                }
25368            }
25369        }
25370    }
25371
25372    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25373        Set<String> unusedPackages = new HashSet<>();
25374        long currentTimeInMillis = System.currentTimeMillis();
25375        synchronized (mPackages) {
25376            for (PackageParser.Package pkg : mPackages.values()) {
25377                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25378                if (ps == null) {
25379                    continue;
25380                }
25381                PackageDexUsage.PackageUseInfo packageUseInfo =
25382                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25383                if (PackageManagerServiceUtils
25384                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25385                                downgradeTimeThresholdMillis, packageUseInfo,
25386                                pkg.getLatestPackageUseTimeInMills(),
25387                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25388                    unusedPackages.add(pkg.packageName);
25389                }
25390            }
25391        }
25392        return unusedPackages;
25393    }
25394}
25395
25396interface PackageSender {
25397    void sendPackageBroadcast(final String action, final String pkg,
25398        final Bundle extras, final int flags, final String targetPkg,
25399        final IIntentReceiver finishedReceiver, final int[] userIds);
25400    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25401        boolean includeStopped, int appId, int... userIds);
25402}
25403