PackageManagerService.java revision cdd685c07504223e37e7831ce592446ec4ac6f6a
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
89import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90import static android.system.OsConstants.O_CREAT;
91import static android.system.OsConstants.O_RDWR;
92
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97import static com.android.internal.util.ArrayUtils.appendInt;
98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
106import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
107import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
108
109import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
110
111import android.Manifest;
112import android.annotation.IntDef;
113import android.annotation.NonNull;
114import android.annotation.Nullable;
115import android.app.ActivityManager;
116import android.app.AppOpsManager;
117import android.app.IActivityManager;
118import android.app.ResourcesManager;
119import android.app.admin.IDevicePolicyManager;
120import android.app.admin.SecurityLog;
121import android.app.backup.IBackupManager;
122import android.content.BroadcastReceiver;
123import android.content.ComponentName;
124import android.content.ContentResolver;
125import android.content.Context;
126import android.content.IIntentReceiver;
127import android.content.Intent;
128import android.content.IntentFilter;
129import android.content.IntentSender;
130import android.content.IntentSender.SendIntentException;
131import android.content.ServiceConnection;
132import android.content.pm.ActivityInfo;
133import android.content.pm.ApplicationInfo;
134import android.content.pm.AppsQueryHelper;
135import android.content.pm.AuxiliaryResolveInfo;
136import android.content.pm.ChangedPackages;
137import android.content.pm.ComponentInfo;
138import android.content.pm.FallbackCategoryProvider;
139import android.content.pm.FeatureInfo;
140import android.content.pm.IDexModuleRegisterCallback;
141import android.content.pm.IOnPermissionsChangeListener;
142import android.content.pm.IPackageDataObserver;
143import android.content.pm.IPackageDeleteObserver;
144import android.content.pm.IPackageDeleteObserver2;
145import android.content.pm.IPackageInstallObserver2;
146import android.content.pm.IPackageInstaller;
147import android.content.pm.IPackageManager;
148import android.content.pm.IPackageManagerNative;
149import android.content.pm.IPackageMoveObserver;
150import android.content.pm.IPackageStatsObserver;
151import android.content.pm.InstantAppInfo;
152import android.content.pm.InstantAppRequest;
153import android.content.pm.InstantAppResolveInfo;
154import android.content.pm.InstrumentationInfo;
155import android.content.pm.IntentFilterVerificationInfo;
156import android.content.pm.KeySet;
157import android.content.pm.PackageCleanItem;
158import android.content.pm.PackageInfo;
159import android.content.pm.PackageInfoLite;
160import android.content.pm.PackageInstaller;
161import android.content.pm.PackageManager;
162import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
163import android.content.pm.PackageManagerInternal;
164import android.content.pm.PackageParser;
165import android.content.pm.PackageParser.ActivityIntentInfo;
166import android.content.pm.PackageParser.PackageLite;
167import android.content.pm.PackageParser.PackageParserException;
168import android.content.pm.PackageStats;
169import android.content.pm.PackageUserState;
170import android.content.pm.ParceledListSlice;
171import android.content.pm.PermissionGroupInfo;
172import android.content.pm.PermissionInfo;
173import android.content.pm.ProviderInfo;
174import android.content.pm.ResolveInfo;
175import android.content.pm.ServiceInfo;
176import android.content.pm.SharedLibraryInfo;
177import android.content.pm.Signature;
178import android.content.pm.UserInfo;
179import android.content.pm.VerifierDeviceIdentity;
180import android.content.pm.VerifierInfo;
181import android.content.pm.VersionedPackage;
182import android.content.res.Resources;
183import android.database.ContentObserver;
184import android.graphics.Bitmap;
185import android.hardware.display.DisplayManager;
186import android.net.Uri;
187import android.os.Binder;
188import android.os.Build;
189import android.os.Bundle;
190import android.os.Debug;
191import android.os.Environment;
192import android.os.Environment.UserEnvironment;
193import android.os.FileUtils;
194import android.os.Handler;
195import android.os.IBinder;
196import android.os.Looper;
197import android.os.Message;
198import android.os.Parcel;
199import android.os.ParcelFileDescriptor;
200import android.os.PatternMatcher;
201import android.os.Process;
202import android.os.RemoteCallbackList;
203import android.os.RemoteException;
204import android.os.ResultReceiver;
205import android.os.SELinux;
206import android.os.ServiceManager;
207import android.os.ShellCallback;
208import android.os.SystemClock;
209import android.os.SystemProperties;
210import android.os.Trace;
211import android.os.UserHandle;
212import android.os.UserManager;
213import android.os.UserManagerInternal;
214import android.os.storage.IStorageManager;
215import android.os.storage.StorageEventListener;
216import android.os.storage.StorageManager;
217import android.os.storage.StorageManagerInternal;
218import android.os.storage.VolumeInfo;
219import android.os.storage.VolumeRecord;
220import android.provider.Settings.Global;
221import android.provider.Settings.Secure;
222import android.security.KeyStore;
223import android.security.SystemKeyStore;
224import android.service.pm.PackageServiceDumpProto;
225import android.system.ErrnoException;
226import android.system.Os;
227import android.text.TextUtils;
228import android.text.format.DateUtils;
229import android.util.ArrayMap;
230import android.util.ArraySet;
231import android.util.Base64;
232import android.util.TimingsTraceLog;
233import android.util.DisplayMetrics;
234import android.util.EventLog;
235import android.util.ExceptionUtils;
236import android.util.Log;
237import android.util.LogPrinter;
238import android.util.MathUtils;
239import android.util.PackageUtils;
240import android.util.Pair;
241import android.util.PrintStreamPrinter;
242import android.util.Slog;
243import android.util.SparseArray;
244import android.util.SparseBooleanArray;
245import android.util.SparseIntArray;
246import android.util.Xml;
247import android.util.jar.StrictJarFile;
248import android.util.proto.ProtoOutputStream;
249import android.view.Display;
250
251import com.android.internal.R;
252import com.android.internal.annotations.GuardedBy;
253import com.android.internal.app.IMediaContainerService;
254import com.android.internal.app.ResolverActivity;
255import com.android.internal.content.NativeLibraryHelper;
256import com.android.internal.content.PackageHelper;
257import com.android.internal.logging.MetricsLogger;
258import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
259import com.android.internal.os.IParcelFileDescriptorFactory;
260import com.android.internal.os.RoSystemProperties;
261import com.android.internal.os.SomeArgs;
262import com.android.internal.os.Zygote;
263import com.android.internal.telephony.CarrierAppUtils;
264import com.android.internal.util.ArrayUtils;
265import com.android.internal.util.ConcurrentUtils;
266import com.android.internal.util.DumpUtils;
267import com.android.internal.util.FastPrintWriter;
268import com.android.internal.util.FastXmlSerializer;
269import com.android.internal.util.IndentingPrintWriter;
270import com.android.internal.util.Preconditions;
271import com.android.internal.util.XmlUtils;
272import com.android.server.AttributeCache;
273import com.android.server.DeviceIdleController;
274import com.android.server.EventLogTags;
275import com.android.server.FgThread;
276import com.android.server.IntentResolver;
277import com.android.server.LocalServices;
278import com.android.server.LockGuard;
279import com.android.server.ServiceThread;
280import com.android.server.SystemConfig;
281import com.android.server.SystemServerInitThreadPool;
282import com.android.server.Watchdog;
283import com.android.server.net.NetworkPolicyManagerInternal;
284import com.android.server.pm.Installer.InstallerException;
285import com.android.server.pm.PermissionsState.PermissionState;
286import com.android.server.pm.Settings.DatabaseVersion;
287import com.android.server.pm.Settings.VersionInfo;
288import com.android.server.pm.dex.DexManager;
289import com.android.server.pm.dex.DexoptOptions;
290import com.android.server.pm.dex.PackageDexUsage;
291import com.android.server.storage.DeviceStorageMonitorInternal;
292
293import dalvik.system.CloseGuard;
294import dalvik.system.DexFile;
295import dalvik.system.VMRuntime;
296
297import libcore.io.IoUtils;
298import libcore.io.Streams;
299import libcore.util.EmptyArray;
300
301import org.xmlpull.v1.XmlPullParser;
302import org.xmlpull.v1.XmlPullParserException;
303import org.xmlpull.v1.XmlSerializer;
304
305import java.io.BufferedOutputStream;
306import java.io.BufferedReader;
307import java.io.ByteArrayInputStream;
308import java.io.ByteArrayOutputStream;
309import java.io.File;
310import java.io.FileDescriptor;
311import java.io.FileInputStream;
312import java.io.FileOutputStream;
313import java.io.FileReader;
314import java.io.FilenameFilter;
315import java.io.IOException;
316import java.io.InputStream;
317import java.io.OutputStream;
318import java.io.PrintWriter;
319import java.lang.annotation.Retention;
320import java.lang.annotation.RetentionPolicy;
321import java.nio.charset.StandardCharsets;
322import java.security.DigestInputStream;
323import java.security.MessageDigest;
324import java.security.NoSuchAlgorithmException;
325import java.security.PublicKey;
326import java.security.SecureRandom;
327import java.security.cert.Certificate;
328import java.security.cert.CertificateEncodingException;
329import java.security.cert.CertificateException;
330import java.text.SimpleDateFormat;
331import java.util.ArrayList;
332import java.util.Arrays;
333import java.util.Collection;
334import java.util.Collections;
335import java.util.Comparator;
336import java.util.Date;
337import java.util.HashMap;
338import java.util.HashSet;
339import java.util.Iterator;
340import java.util.List;
341import java.util.Map;
342import java.util.Objects;
343import java.util.Set;
344import java.util.concurrent.CountDownLatch;
345import java.util.concurrent.Future;
346import java.util.concurrent.TimeUnit;
347import java.util.concurrent.atomic.AtomicBoolean;
348import java.util.concurrent.atomic.AtomicInteger;
349import java.util.zip.GZIPInputStream;
350
351/**
352 * Keep track of all those APKs everywhere.
353 * <p>
354 * Internally there are two important locks:
355 * <ul>
356 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
357 * and other related state. It is a fine-grained lock that should only be held
358 * momentarily, as it's one of the most contended locks in the system.
359 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
360 * operations typically involve heavy lifting of application data on disk. Since
361 * {@code installd} is single-threaded, and it's operations can often be slow,
362 * this lock should never be acquired while already holding {@link #mPackages}.
363 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
364 * holding {@link #mInstallLock}.
365 * </ul>
366 * Many internal methods rely on the caller to hold the appropriate locks, and
367 * this contract is expressed through method name suffixes:
368 * <ul>
369 * <li>fooLI(): the caller must hold {@link #mInstallLock}
370 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
371 * being modified must be frozen
372 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
373 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
374 * </ul>
375 * <p>
376 * Because this class is very central to the platform's security; please run all
377 * CTS and unit tests whenever making modifications:
378 *
379 * <pre>
380 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
381 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
382 * </pre>
383 */
384public class PackageManagerService extends IPackageManager.Stub
385        implements PackageSender {
386    static final String TAG = "PackageManager";
387    static final boolean DEBUG_SETTINGS = false;
388    static final boolean DEBUG_PREFERRED = false;
389    static final boolean DEBUG_UPGRADE = false;
390    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
391    private static final boolean DEBUG_BACKUP = false;
392    private static final boolean DEBUG_INSTALL = false;
393    private static final boolean DEBUG_REMOVE = false;
394    private static final boolean DEBUG_BROADCASTS = false;
395    private static final boolean DEBUG_SHOW_INFO = false;
396    private static final boolean DEBUG_PACKAGE_INFO = false;
397    private static final boolean DEBUG_INTENT_MATCHING = false;
398    private static final boolean DEBUG_PACKAGE_SCANNING = false;
399    private static final boolean DEBUG_VERIFY = false;
400    private static final boolean DEBUG_FILTERS = false;
401    private static final boolean DEBUG_PERMISSIONS = false;
402    private static final boolean DEBUG_SHARED_LIBRARIES = false;
403    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
404
405    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
406    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
407    // user, but by default initialize to this.
408    public static final boolean DEBUG_DEXOPT = false;
409
410    private static final boolean DEBUG_ABI_SELECTION = false;
411    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
412    private static final boolean DEBUG_TRIAGED_MISSING = false;
413    private static final boolean DEBUG_APP_DATA = false;
414
415    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
416    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
417
418    private static final boolean HIDE_EPHEMERAL_APIS = false;
419
420    private static final boolean ENABLE_FREE_CACHE_V2 =
421            SystemProperties.getBoolean("fw.free_cache_v2", true);
422
423    private static final int RADIO_UID = Process.PHONE_UID;
424    private static final int LOG_UID = Process.LOG_UID;
425    private static final int NFC_UID = Process.NFC_UID;
426    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
427    private static final int SHELL_UID = Process.SHELL_UID;
428
429    // Cap the size of permission trees that 3rd party apps can define
430    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
431
432    // Suffix used during package installation when copying/moving
433    // package apks to install directory.
434    private static final String INSTALL_PACKAGE_SUFFIX = "-";
435
436    static final int SCAN_NO_DEX = 1<<1;
437    static final int SCAN_FORCE_DEX = 1<<2;
438    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
439    static final int SCAN_NEW_INSTALL = 1<<4;
440    static final int SCAN_UPDATE_TIME = 1<<5;
441    static final int SCAN_BOOTING = 1<<6;
442    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
443    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
444    static final int SCAN_REPLACING = 1<<9;
445    static final int SCAN_REQUIRE_KNOWN = 1<<10;
446    static final int SCAN_MOVE = 1<<11;
447    static final int SCAN_INITIAL = 1<<12;
448    static final int SCAN_CHECK_ONLY = 1<<13;
449    static final int SCAN_DONT_KILL_APP = 1<<14;
450    static final int SCAN_IGNORE_FROZEN = 1<<15;
451    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
452    static final int SCAN_AS_INSTANT_APP = 1<<17;
453    static final int SCAN_AS_FULL_APP = 1<<18;
454    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
455    /** Should not be with the scan flags */
456    static final int FLAGS_REMOVE_CHATTY = 1<<31;
457
458    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
459    /** Extension of the compressed packages */
460    private final static String COMPRESSED_EXTENSION = ".gz";
461    /** Suffix of stub packages on the system partition */
462    private final static String STUB_SUFFIX = "-Stub";
463
464    private static final int[] EMPTY_INT_ARRAY = new int[0];
465
466    private static final int TYPE_UNKNOWN = 0;
467    private static final int TYPE_ACTIVITY = 1;
468    private static final int TYPE_RECEIVER = 2;
469    private static final int TYPE_SERVICE = 3;
470    private static final int TYPE_PROVIDER = 4;
471    @IntDef(prefix = { "TYPE_" }, value = {
472            TYPE_UNKNOWN,
473            TYPE_ACTIVITY,
474            TYPE_RECEIVER,
475            TYPE_SERVICE,
476            TYPE_PROVIDER,
477    })
478    @Retention(RetentionPolicy.SOURCE)
479    public @interface ComponentType {}
480
481    /**
482     * Timeout (in milliseconds) after which the watchdog should declare that
483     * our handler thread is wedged.  The usual default for such things is one
484     * minute but we sometimes do very lengthy I/O operations on this thread,
485     * such as installing multi-gigabyte applications, so ours needs to be longer.
486     */
487    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
488
489    /**
490     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
491     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
492     * settings entry if available, otherwise we use the hardcoded default.  If it's been
493     * more than this long since the last fstrim, we force one during the boot sequence.
494     *
495     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
496     * one gets run at the next available charging+idle time.  This final mandatory
497     * no-fstrim check kicks in only of the other scheduling criteria is never met.
498     */
499    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
500
501    /**
502     * Whether verification is enabled by default.
503     */
504    private static final boolean DEFAULT_VERIFY_ENABLE = true;
505
506    /**
507     * The default maximum time to wait for the verification agent to return in
508     * milliseconds.
509     */
510    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
511
512    /**
513     * The default response for package verification timeout.
514     *
515     * This can be either PackageManager.VERIFICATION_ALLOW or
516     * PackageManager.VERIFICATION_REJECT.
517     */
518    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
519
520    static final String PLATFORM_PACKAGE_NAME = "android";
521
522    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
523
524    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
525            DEFAULT_CONTAINER_PACKAGE,
526            "com.android.defcontainer.DefaultContainerService");
527
528    private static final String KILL_APP_REASON_GIDS_CHANGED =
529            "permission grant or revoke changed gids";
530
531    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
532            "permissions revoked";
533
534    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
535
536    private static final String PACKAGE_SCHEME = "package";
537
538    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
539
540    /** Permission grant: not grant the permission. */
541    private static final int GRANT_DENIED = 1;
542
543    /** Permission grant: grant the permission as an install permission. */
544    private static final int GRANT_INSTALL = 2;
545
546    /** Permission grant: grant the permission as a runtime one. */
547    private static final int GRANT_RUNTIME = 3;
548
549    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
550    private static final int GRANT_UPGRADE = 4;
551
552    /** Canonical intent used to identify what counts as a "web browser" app */
553    private static final Intent sBrowserIntent;
554    static {
555        sBrowserIntent = new Intent();
556        sBrowserIntent.setAction(Intent.ACTION_VIEW);
557        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
558        sBrowserIntent.setData(Uri.parse("http:"));
559    }
560
561    /**
562     * The set of all protected actions [i.e. those actions for which a high priority
563     * intent filter is disallowed].
564     */
565    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
566    static {
567        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
568        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
569        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
570        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
571    }
572
573    // Compilation reasons.
574    public static final int REASON_FIRST_BOOT = 0;
575    public static final int REASON_BOOT = 1;
576    public static final int REASON_INSTALL = 2;
577    public static final int REASON_BACKGROUND_DEXOPT = 3;
578    public static final int REASON_AB_OTA = 4;
579    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
580
581    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
582
583    /** All dangerous permission names in the same order as the events in MetricsEvent */
584    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
585            Manifest.permission.READ_CALENDAR,
586            Manifest.permission.WRITE_CALENDAR,
587            Manifest.permission.CAMERA,
588            Manifest.permission.READ_CONTACTS,
589            Manifest.permission.WRITE_CONTACTS,
590            Manifest.permission.GET_ACCOUNTS,
591            Manifest.permission.ACCESS_FINE_LOCATION,
592            Manifest.permission.ACCESS_COARSE_LOCATION,
593            Manifest.permission.RECORD_AUDIO,
594            Manifest.permission.READ_PHONE_STATE,
595            Manifest.permission.CALL_PHONE,
596            Manifest.permission.READ_CALL_LOG,
597            Manifest.permission.WRITE_CALL_LOG,
598            Manifest.permission.ADD_VOICEMAIL,
599            Manifest.permission.USE_SIP,
600            Manifest.permission.PROCESS_OUTGOING_CALLS,
601            Manifest.permission.READ_CELL_BROADCASTS,
602            Manifest.permission.BODY_SENSORS,
603            Manifest.permission.SEND_SMS,
604            Manifest.permission.RECEIVE_SMS,
605            Manifest.permission.READ_SMS,
606            Manifest.permission.RECEIVE_WAP_PUSH,
607            Manifest.permission.RECEIVE_MMS,
608            Manifest.permission.READ_EXTERNAL_STORAGE,
609            Manifest.permission.WRITE_EXTERNAL_STORAGE,
610            Manifest.permission.READ_PHONE_NUMBERS,
611            Manifest.permission.ANSWER_PHONE_CALLS);
612
613
614    /**
615     * Version number for the package parser cache. Increment this whenever the format or
616     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
617     */
618    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
619
620    /**
621     * Whether the package parser cache is enabled.
622     */
623    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
624
625    final ServiceThread mHandlerThread;
626
627    final PackageHandler mHandler;
628
629    private final ProcessLoggingHandler mProcessLoggingHandler;
630
631    /**
632     * Messages for {@link #mHandler} that need to wait for system ready before
633     * being dispatched.
634     */
635    private ArrayList<Message> mPostSystemReadyMessages;
636
637    final int mSdkVersion = Build.VERSION.SDK_INT;
638
639    final Context mContext;
640    final boolean mFactoryTest;
641    final boolean mOnlyCore;
642    final DisplayMetrics mMetrics;
643    final int mDefParseFlags;
644    final String[] mSeparateProcesses;
645    final boolean mIsUpgrade;
646    final boolean mIsPreNUpgrade;
647    final boolean mIsPreNMR1Upgrade;
648
649    // Have we told the Activity Manager to whitelist the default container service by uid yet?
650    @GuardedBy("mPackages")
651    boolean mDefaultContainerWhitelisted = false;
652
653    @GuardedBy("mPackages")
654    private boolean mDexOptDialogShown;
655
656    /** The location for ASEC container files on internal storage. */
657    final String mAsecInternalPath;
658
659    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
660    // LOCK HELD.  Can be called with mInstallLock held.
661    @GuardedBy("mInstallLock")
662    final Installer mInstaller;
663
664    /** Directory where installed third-party apps stored */
665    final File mAppInstallDir;
666
667    /**
668     * Directory to which applications installed internally have their
669     * 32 bit native libraries copied.
670     */
671    private File mAppLib32InstallDir;
672
673    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
674    // apps.
675    final File mDrmAppPrivateInstallDir;
676
677    // ----------------------------------------------------------------
678
679    // Lock for state used when installing and doing other long running
680    // operations.  Methods that must be called with this lock held have
681    // the suffix "LI".
682    final Object mInstallLock = new Object();
683
684    // ----------------------------------------------------------------
685
686    // Keys are String (package name), values are Package.  This also serves
687    // as the lock for the global state.  Methods that must be called with
688    // this lock held have the prefix "LP".
689    @GuardedBy("mPackages")
690    final ArrayMap<String, PackageParser.Package> mPackages =
691            new ArrayMap<String, PackageParser.Package>();
692
693    final ArrayMap<String, Set<String>> mKnownCodebase =
694            new ArrayMap<String, Set<String>>();
695
696    // Keys are isolated uids and values are the uid of the application
697    // that created the isolated proccess.
698    @GuardedBy("mPackages")
699    final SparseIntArray mIsolatedOwners = new SparseIntArray();
700
701    /**
702     * Tracks new system packages [received in an OTA] that we expect to
703     * find updated user-installed versions. Keys are package name, values
704     * are package location.
705     */
706    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
707    /**
708     * Tracks high priority intent filters for protected actions. During boot, certain
709     * filter actions are protected and should never be allowed to have a high priority
710     * intent filter for them. However, there is one, and only one exception -- the
711     * setup wizard. It must be able to define a high priority intent filter for these
712     * actions to ensure there are no escapes from the wizard. We need to delay processing
713     * of these during boot as we need to look at all of the system packages in order
714     * to know which component is the setup wizard.
715     */
716    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
717    /**
718     * Whether or not processing protected filters should be deferred.
719     */
720    private boolean mDeferProtectedFilters = true;
721
722    /**
723     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
724     */
725    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
726    /**
727     * Whether or not system app permissions should be promoted from install to runtime.
728     */
729    boolean mPromoteSystemApps;
730
731    @GuardedBy("mPackages")
732    final Settings mSettings;
733
734    /**
735     * Set of package names that are currently "frozen", which means active
736     * surgery is being done on the code/data for that package. The platform
737     * will refuse to launch frozen packages to avoid race conditions.
738     *
739     * @see PackageFreezer
740     */
741    @GuardedBy("mPackages")
742    final ArraySet<String> mFrozenPackages = new ArraySet<>();
743
744    final ProtectedPackages mProtectedPackages;
745
746    @GuardedBy("mLoadedVolumes")
747    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
748
749    boolean mFirstBoot;
750
751    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
752
753    // System configuration read by SystemConfig.
754    final int[] mGlobalGids;
755    final SparseArray<ArraySet<String>> mSystemPermissions;
756    @GuardedBy("mAvailableFeatures")
757    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
758
759    // If mac_permissions.xml was found for seinfo labeling.
760    boolean mFoundPolicyFile;
761
762    private final InstantAppRegistry mInstantAppRegistry;
763
764    @GuardedBy("mPackages")
765    int mChangedPackagesSequenceNumber;
766    /**
767     * List of changed [installed, removed or updated] packages.
768     * mapping from user id -> sequence number -> package name
769     */
770    @GuardedBy("mPackages")
771    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
772    /**
773     * The sequence number of the last change to a package.
774     * mapping from user id -> package name -> sequence number
775     */
776    @GuardedBy("mPackages")
777    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
778
779    class PackageParserCallback implements PackageParser.Callback {
780        @Override public final boolean hasFeature(String feature) {
781            return PackageManagerService.this.hasSystemFeature(feature, 0);
782        }
783
784        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
785                Collection<PackageParser.Package> allPackages, String targetPackageName) {
786            List<PackageParser.Package> overlayPackages = null;
787            for (PackageParser.Package p : allPackages) {
788                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
789                    if (overlayPackages == null) {
790                        overlayPackages = new ArrayList<PackageParser.Package>();
791                    }
792                    overlayPackages.add(p);
793                }
794            }
795            if (overlayPackages != null) {
796                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
797                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
798                        return p1.mOverlayPriority - p2.mOverlayPriority;
799                    }
800                };
801                Collections.sort(overlayPackages, cmp);
802            }
803            return overlayPackages;
804        }
805
806        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
807                String targetPackageName, String targetPath) {
808            if ("android".equals(targetPackageName)) {
809                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
810                // native AssetManager.
811                return null;
812            }
813            List<PackageParser.Package> overlayPackages =
814                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
815            if (overlayPackages == null || overlayPackages.isEmpty()) {
816                return null;
817            }
818            List<String> overlayPathList = null;
819            for (PackageParser.Package overlayPackage : overlayPackages) {
820                if (targetPath == null) {
821                    if (overlayPathList == null) {
822                        overlayPathList = new ArrayList<String>();
823                    }
824                    overlayPathList.add(overlayPackage.baseCodePath);
825                    continue;
826                }
827
828                try {
829                    // Creates idmaps for system to parse correctly the Android manifest of the
830                    // target package.
831                    //
832                    // OverlayManagerService will update each of them with a correct gid from its
833                    // target package app id.
834                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
835                            UserHandle.getSharedAppGid(
836                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
837                    if (overlayPathList == null) {
838                        overlayPathList = new ArrayList<String>();
839                    }
840                    overlayPathList.add(overlayPackage.baseCodePath);
841                } catch (InstallerException e) {
842                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
843                            overlayPackage.baseCodePath);
844                }
845            }
846            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
847        }
848
849        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
850            synchronized (mPackages) {
851                return getStaticOverlayPathsLocked(
852                        mPackages.values(), targetPackageName, targetPath);
853            }
854        }
855
856        @Override public final String[] getOverlayApks(String targetPackageName) {
857            return getStaticOverlayPaths(targetPackageName, null);
858        }
859
860        @Override public final String[] getOverlayPaths(String targetPackageName,
861                String targetPath) {
862            return getStaticOverlayPaths(targetPackageName, targetPath);
863        }
864    };
865
866    class ParallelPackageParserCallback extends PackageParserCallback {
867        List<PackageParser.Package> mOverlayPackages = null;
868
869        void findStaticOverlayPackages() {
870            synchronized (mPackages) {
871                for (PackageParser.Package p : mPackages.values()) {
872                    if (p.mIsStaticOverlay) {
873                        if (mOverlayPackages == null) {
874                            mOverlayPackages = new ArrayList<PackageParser.Package>();
875                        }
876                        mOverlayPackages.add(p);
877                    }
878                }
879            }
880        }
881
882        @Override
883        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
884            // We can trust mOverlayPackages without holding mPackages because package uninstall
885            // can't happen while running parallel parsing.
886            // Moreover holding mPackages on each parsing thread causes dead-lock.
887            return mOverlayPackages == null ? null :
888                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
889        }
890    }
891
892    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
893    final ParallelPackageParserCallback mParallelPackageParserCallback =
894            new ParallelPackageParserCallback();
895
896    public static final class SharedLibraryEntry {
897        public final @Nullable String path;
898        public final @Nullable String apk;
899        public final @NonNull SharedLibraryInfo info;
900
901        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
902                String declaringPackageName, int declaringPackageVersionCode) {
903            path = _path;
904            apk = _apk;
905            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
906                    declaringPackageName, declaringPackageVersionCode), null);
907        }
908    }
909
910    // Currently known shared libraries.
911    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
912    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
913            new ArrayMap<>();
914
915    // All available activities, for your resolving pleasure.
916    final ActivityIntentResolver mActivities =
917            new ActivityIntentResolver();
918
919    // All available receivers, for your resolving pleasure.
920    final ActivityIntentResolver mReceivers =
921            new ActivityIntentResolver();
922
923    // All available services, for your resolving pleasure.
924    final ServiceIntentResolver mServices = new ServiceIntentResolver();
925
926    // All available providers, for your resolving pleasure.
927    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
928
929    // Mapping from provider base names (first directory in content URI codePath)
930    // to the provider information.
931    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
932            new ArrayMap<String, PackageParser.Provider>();
933
934    // Mapping from instrumentation class names to info about them.
935    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
936            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
937
938    // Mapping from permission names to info about them.
939    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
940            new ArrayMap<String, PackageParser.PermissionGroup>();
941
942    // Packages whose data we have transfered into another package, thus
943    // should no longer exist.
944    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
945
946    // Broadcast actions that are only available to the system.
947    @GuardedBy("mProtectedBroadcasts")
948    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
949
950    /** List of packages waiting for verification. */
951    final SparseArray<PackageVerificationState> mPendingVerification
952            = new SparseArray<PackageVerificationState>();
953
954    /** Set of packages associated with each app op permission. */
955    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
956
957    final PackageInstallerService mInstallerService;
958
959    private final PackageDexOptimizer mPackageDexOptimizer;
960    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
961    // is used by other apps).
962    private final DexManager mDexManager;
963
964    private AtomicInteger mNextMoveId = new AtomicInteger();
965    private final MoveCallbacks mMoveCallbacks;
966
967    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
968
969    // Cache of users who need badging.
970    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
971
972    /** Token for keys in mPendingVerification. */
973    private int mPendingVerificationToken = 0;
974
975    volatile boolean mSystemReady;
976    volatile boolean mSafeMode;
977    volatile boolean mHasSystemUidErrors;
978    private volatile boolean mEphemeralAppsDisabled;
979
980    ApplicationInfo mAndroidApplication;
981    final ActivityInfo mResolveActivity = new ActivityInfo();
982    final ResolveInfo mResolveInfo = new ResolveInfo();
983    ComponentName mResolveComponentName;
984    PackageParser.Package mPlatformPackage;
985    ComponentName mCustomResolverComponentName;
986
987    boolean mResolverReplaced = false;
988
989    private final @Nullable ComponentName mIntentFilterVerifierComponent;
990    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
991
992    private int mIntentFilterVerificationToken = 0;
993
994    /** The service connection to the ephemeral resolver */
995    final EphemeralResolverConnection mInstantAppResolverConnection;
996    /** Component used to show resolver settings for Instant Apps */
997    final ComponentName mInstantAppResolverSettingsComponent;
998
999    /** Activity used to install instant applications */
1000    ActivityInfo mInstantAppInstallerActivity;
1001    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1002
1003    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1004            = new SparseArray<IntentFilterVerificationState>();
1005
1006    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1007
1008    // List of packages names to keep cached, even if they are uninstalled for all users
1009    private List<String> mKeepUninstalledPackages;
1010
1011    private UserManagerInternal mUserManagerInternal;
1012
1013    private DeviceIdleController.LocalService mDeviceIdleController;
1014
1015    private File mCacheDir;
1016
1017    private ArraySet<String> mPrivappPermissionsViolations;
1018
1019    private Future<?> mPrepareAppDataFuture;
1020
1021    private static class IFVerificationParams {
1022        PackageParser.Package pkg;
1023        boolean replacing;
1024        int userId;
1025        int verifierUid;
1026
1027        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1028                int _userId, int _verifierUid) {
1029            pkg = _pkg;
1030            replacing = _replacing;
1031            userId = _userId;
1032            replacing = _replacing;
1033            verifierUid = _verifierUid;
1034        }
1035    }
1036
1037    private interface IntentFilterVerifier<T extends IntentFilter> {
1038        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1039                                               T filter, String packageName);
1040        void startVerifications(int userId);
1041        void receiveVerificationResponse(int verificationId);
1042    }
1043
1044    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1045        private Context mContext;
1046        private ComponentName mIntentFilterVerifierComponent;
1047        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1048
1049        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1050            mContext = context;
1051            mIntentFilterVerifierComponent = verifierComponent;
1052        }
1053
1054        private String getDefaultScheme() {
1055            return IntentFilter.SCHEME_HTTPS;
1056        }
1057
1058        @Override
1059        public void startVerifications(int userId) {
1060            // Launch verifications requests
1061            int count = mCurrentIntentFilterVerifications.size();
1062            for (int n=0; n<count; n++) {
1063                int verificationId = mCurrentIntentFilterVerifications.get(n);
1064                final IntentFilterVerificationState ivs =
1065                        mIntentFilterVerificationStates.get(verificationId);
1066
1067                String packageName = ivs.getPackageName();
1068
1069                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1070                final int filterCount = filters.size();
1071                ArraySet<String> domainsSet = new ArraySet<>();
1072                for (int m=0; m<filterCount; m++) {
1073                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1074                    domainsSet.addAll(filter.getHostsList());
1075                }
1076                synchronized (mPackages) {
1077                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1078                            packageName, domainsSet) != null) {
1079                        scheduleWriteSettingsLocked();
1080                    }
1081                }
1082                sendVerificationRequest(verificationId, ivs);
1083            }
1084            mCurrentIntentFilterVerifications.clear();
1085        }
1086
1087        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1088            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1089            verificationIntent.putExtra(
1090                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1091                    verificationId);
1092            verificationIntent.putExtra(
1093                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1094                    getDefaultScheme());
1095            verificationIntent.putExtra(
1096                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1097                    ivs.getHostsString());
1098            verificationIntent.putExtra(
1099                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1100                    ivs.getPackageName());
1101            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1102            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1103
1104            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1105            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1106                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1107                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1108
1109            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1110            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1111                    "Sending IntentFilter verification broadcast");
1112        }
1113
1114        public void receiveVerificationResponse(int verificationId) {
1115            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1116
1117            final boolean verified = ivs.isVerified();
1118
1119            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1120            final int count = filters.size();
1121            if (DEBUG_DOMAIN_VERIFICATION) {
1122                Slog.i(TAG, "Received verification response " + verificationId
1123                        + " for " + count + " filters, verified=" + verified);
1124            }
1125            for (int n=0; n<count; n++) {
1126                PackageParser.ActivityIntentInfo filter = filters.get(n);
1127                filter.setVerified(verified);
1128
1129                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1130                        + " verified with result:" + verified + " and hosts:"
1131                        + ivs.getHostsString());
1132            }
1133
1134            mIntentFilterVerificationStates.remove(verificationId);
1135
1136            final String packageName = ivs.getPackageName();
1137            IntentFilterVerificationInfo ivi = null;
1138
1139            synchronized (mPackages) {
1140                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1141            }
1142            if (ivi == null) {
1143                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1144                        + verificationId + " packageName:" + packageName);
1145                return;
1146            }
1147            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1148                    "Updating IntentFilterVerificationInfo for package " + packageName
1149                            +" verificationId:" + verificationId);
1150
1151            synchronized (mPackages) {
1152                if (verified) {
1153                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1154                } else {
1155                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1156                }
1157                scheduleWriteSettingsLocked();
1158
1159                final int userId = ivs.getUserId();
1160                if (userId != UserHandle.USER_ALL) {
1161                    final int userStatus =
1162                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1163
1164                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1165                    boolean needUpdate = false;
1166
1167                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1168                    // already been set by the User thru the Disambiguation dialog
1169                    switch (userStatus) {
1170                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1171                            if (verified) {
1172                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1173                            } else {
1174                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1175                            }
1176                            needUpdate = true;
1177                            break;
1178
1179                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1180                            if (verified) {
1181                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1182                                needUpdate = true;
1183                            }
1184                            break;
1185
1186                        default:
1187                            // Nothing to do
1188                    }
1189
1190                    if (needUpdate) {
1191                        mSettings.updateIntentFilterVerificationStatusLPw(
1192                                packageName, updatedStatus, userId);
1193                        scheduleWritePackageRestrictionsLocked(userId);
1194                    }
1195                }
1196            }
1197        }
1198
1199        @Override
1200        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1201                    ActivityIntentInfo filter, String packageName) {
1202            if (!hasValidDomains(filter)) {
1203                return false;
1204            }
1205            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1206            if (ivs == null) {
1207                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1208                        packageName);
1209            }
1210            if (DEBUG_DOMAIN_VERIFICATION) {
1211                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1212            }
1213            ivs.addFilter(filter);
1214            return true;
1215        }
1216
1217        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1218                int userId, int verificationId, String packageName) {
1219            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1220                    verifierUid, userId, packageName);
1221            ivs.setPendingState();
1222            synchronized (mPackages) {
1223                mIntentFilterVerificationStates.append(verificationId, ivs);
1224                mCurrentIntentFilterVerifications.add(verificationId);
1225            }
1226            return ivs;
1227        }
1228    }
1229
1230    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1231        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1232                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1233                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1234    }
1235
1236    // Set of pending broadcasts for aggregating enable/disable of components.
1237    static class PendingPackageBroadcasts {
1238        // for each user id, a map of <package name -> components within that package>
1239        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1240
1241        public PendingPackageBroadcasts() {
1242            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1243        }
1244
1245        public ArrayList<String> get(int userId, String packageName) {
1246            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1247            return packages.get(packageName);
1248        }
1249
1250        public void put(int userId, String packageName, ArrayList<String> components) {
1251            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1252            packages.put(packageName, components);
1253        }
1254
1255        public void remove(int userId, String packageName) {
1256            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1257            if (packages != null) {
1258                packages.remove(packageName);
1259            }
1260        }
1261
1262        public void remove(int userId) {
1263            mUidMap.remove(userId);
1264        }
1265
1266        public int userIdCount() {
1267            return mUidMap.size();
1268        }
1269
1270        public int userIdAt(int n) {
1271            return mUidMap.keyAt(n);
1272        }
1273
1274        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1275            return mUidMap.get(userId);
1276        }
1277
1278        public int size() {
1279            // total number of pending broadcast entries across all userIds
1280            int num = 0;
1281            for (int i = 0; i< mUidMap.size(); i++) {
1282                num += mUidMap.valueAt(i).size();
1283            }
1284            return num;
1285        }
1286
1287        public void clear() {
1288            mUidMap.clear();
1289        }
1290
1291        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1292            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1293            if (map == null) {
1294                map = new ArrayMap<String, ArrayList<String>>();
1295                mUidMap.put(userId, map);
1296            }
1297            return map;
1298        }
1299    }
1300    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1301
1302    // Service Connection to remote media container service to copy
1303    // package uri's from external media onto secure containers
1304    // or internal storage.
1305    private IMediaContainerService mContainerService = null;
1306
1307    static final int SEND_PENDING_BROADCAST = 1;
1308    static final int MCS_BOUND = 3;
1309    static final int END_COPY = 4;
1310    static final int INIT_COPY = 5;
1311    static final int MCS_UNBIND = 6;
1312    static final int START_CLEANING_PACKAGE = 7;
1313    static final int FIND_INSTALL_LOC = 8;
1314    static final int POST_INSTALL = 9;
1315    static final int MCS_RECONNECT = 10;
1316    static final int MCS_GIVE_UP = 11;
1317    static final int UPDATED_MEDIA_STATUS = 12;
1318    static final int WRITE_SETTINGS = 13;
1319    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1320    static final int PACKAGE_VERIFIED = 15;
1321    static final int CHECK_PENDING_VERIFICATION = 16;
1322    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1323    static final int INTENT_FILTER_VERIFIED = 18;
1324    static final int WRITE_PACKAGE_LIST = 19;
1325    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1326
1327    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1328
1329    // Delay time in millisecs
1330    static final int BROADCAST_DELAY = 10 * 1000;
1331
1332    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1333            2 * 60 * 60 * 1000L; /* two hours */
1334
1335    static UserManagerService sUserManager;
1336
1337    // Stores a list of users whose package restrictions file needs to be updated
1338    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1339
1340    final private DefaultContainerConnection mDefContainerConn =
1341            new DefaultContainerConnection();
1342    class DefaultContainerConnection implements ServiceConnection {
1343        public void onServiceConnected(ComponentName name, IBinder service) {
1344            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1345            final IMediaContainerService imcs = IMediaContainerService.Stub
1346                    .asInterface(Binder.allowBlocking(service));
1347            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1348        }
1349
1350        public void onServiceDisconnected(ComponentName name) {
1351            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1352        }
1353    }
1354
1355    // Recordkeeping of restore-after-install operations that are currently in flight
1356    // between the Package Manager and the Backup Manager
1357    static class PostInstallData {
1358        public InstallArgs args;
1359        public PackageInstalledInfo res;
1360
1361        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1362            args = _a;
1363            res = _r;
1364        }
1365    }
1366
1367    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1368    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1369
1370    // XML tags for backup/restore of various bits of state
1371    private static final String TAG_PREFERRED_BACKUP = "pa";
1372    private static final String TAG_DEFAULT_APPS = "da";
1373    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1374
1375    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1376    private static final String TAG_ALL_GRANTS = "rt-grants";
1377    private static final String TAG_GRANT = "grant";
1378    private static final String ATTR_PACKAGE_NAME = "pkg";
1379
1380    private static final String TAG_PERMISSION = "perm";
1381    private static final String ATTR_PERMISSION_NAME = "name";
1382    private static final String ATTR_IS_GRANTED = "g";
1383    private static final String ATTR_USER_SET = "set";
1384    private static final String ATTR_USER_FIXED = "fixed";
1385    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1386
1387    // System/policy permission grants are not backed up
1388    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1389            FLAG_PERMISSION_POLICY_FIXED
1390            | FLAG_PERMISSION_SYSTEM_FIXED
1391            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1392
1393    // And we back up these user-adjusted states
1394    private static final int USER_RUNTIME_GRANT_MASK =
1395            FLAG_PERMISSION_USER_SET
1396            | FLAG_PERMISSION_USER_FIXED
1397            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1398
1399    final @Nullable String mRequiredVerifierPackage;
1400    final @NonNull String mRequiredInstallerPackage;
1401    final @NonNull String mRequiredUninstallerPackage;
1402    final @Nullable String mSetupWizardPackage;
1403    final @Nullable String mStorageManagerPackage;
1404    final @NonNull String mServicesSystemSharedLibraryPackageName;
1405    final @NonNull String mSharedSystemSharedLibraryPackageName;
1406
1407    final boolean mPermissionReviewRequired;
1408
1409    private final PackageUsage mPackageUsage = new PackageUsage();
1410    private final CompilerStats mCompilerStats = new CompilerStats();
1411
1412    class PackageHandler extends Handler {
1413        private boolean mBound = false;
1414        final ArrayList<HandlerParams> mPendingInstalls =
1415            new ArrayList<HandlerParams>();
1416
1417        private boolean connectToService() {
1418            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1419                    " DefaultContainerService");
1420            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1421            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1422            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1423                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1424                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425                mBound = true;
1426                return true;
1427            }
1428            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1429            return false;
1430        }
1431
1432        private void disconnectService() {
1433            mContainerService = null;
1434            mBound = false;
1435            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1436            mContext.unbindService(mDefContainerConn);
1437            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1438        }
1439
1440        PackageHandler(Looper looper) {
1441            super(looper);
1442        }
1443
1444        public void handleMessage(Message msg) {
1445            try {
1446                doHandleMessage(msg);
1447            } finally {
1448                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1449            }
1450        }
1451
1452        void doHandleMessage(Message msg) {
1453            switch (msg.what) {
1454                case INIT_COPY: {
1455                    HandlerParams params = (HandlerParams) msg.obj;
1456                    int idx = mPendingInstalls.size();
1457                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1458                    // If a bind was already initiated we dont really
1459                    // need to do anything. The pending install
1460                    // will be processed later on.
1461                    if (!mBound) {
1462                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1463                                System.identityHashCode(mHandler));
1464                        // If this is the only one pending we might
1465                        // have to bind to the service again.
1466                        if (!connectToService()) {
1467                            Slog.e(TAG, "Failed to bind to media container service");
1468                            params.serviceError();
1469                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1470                                    System.identityHashCode(mHandler));
1471                            if (params.traceMethod != null) {
1472                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1473                                        params.traceCookie);
1474                            }
1475                            return;
1476                        } else {
1477                            // Once we bind to the service, the first
1478                            // pending request will be processed.
1479                            mPendingInstalls.add(idx, params);
1480                        }
1481                    } else {
1482                        mPendingInstalls.add(idx, params);
1483                        // Already bound to the service. Just make
1484                        // sure we trigger off processing the first request.
1485                        if (idx == 0) {
1486                            mHandler.sendEmptyMessage(MCS_BOUND);
1487                        }
1488                    }
1489                    break;
1490                }
1491                case MCS_BOUND: {
1492                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1493                    if (msg.obj != null) {
1494                        mContainerService = (IMediaContainerService) msg.obj;
1495                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1496                                System.identityHashCode(mHandler));
1497                    }
1498                    if (mContainerService == null) {
1499                        if (!mBound) {
1500                            // Something seriously wrong since we are not bound and we are not
1501                            // waiting for connection. Bail out.
1502                            Slog.e(TAG, "Cannot bind to media container service");
1503                            for (HandlerParams params : mPendingInstalls) {
1504                                // Indicate service bind error
1505                                params.serviceError();
1506                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1507                                        System.identityHashCode(params));
1508                                if (params.traceMethod != null) {
1509                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1510                                            params.traceMethod, params.traceCookie);
1511                                }
1512                                return;
1513                            }
1514                            mPendingInstalls.clear();
1515                        } else {
1516                            Slog.w(TAG, "Waiting to connect to media container service");
1517                        }
1518                    } else if (mPendingInstalls.size() > 0) {
1519                        HandlerParams params = mPendingInstalls.get(0);
1520                        if (params != null) {
1521                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1522                                    System.identityHashCode(params));
1523                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1524                            if (params.startCopy()) {
1525                                // We are done...  look for more work or to
1526                                // go idle.
1527                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1528                                        "Checking for more work or unbind...");
1529                                // Delete pending install
1530                                if (mPendingInstalls.size() > 0) {
1531                                    mPendingInstalls.remove(0);
1532                                }
1533                                if (mPendingInstalls.size() == 0) {
1534                                    if (mBound) {
1535                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1536                                                "Posting delayed MCS_UNBIND");
1537                                        removeMessages(MCS_UNBIND);
1538                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1539                                        // Unbind after a little delay, to avoid
1540                                        // continual thrashing.
1541                                        sendMessageDelayed(ubmsg, 10000);
1542                                    }
1543                                } else {
1544                                    // There are more pending requests in queue.
1545                                    // Just post MCS_BOUND message to trigger processing
1546                                    // of next pending install.
1547                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1548                                            "Posting MCS_BOUND for next work");
1549                                    mHandler.sendEmptyMessage(MCS_BOUND);
1550                                }
1551                            }
1552                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1553                        }
1554                    } else {
1555                        // Should never happen ideally.
1556                        Slog.w(TAG, "Empty queue");
1557                    }
1558                    break;
1559                }
1560                case MCS_RECONNECT: {
1561                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1562                    if (mPendingInstalls.size() > 0) {
1563                        if (mBound) {
1564                            disconnectService();
1565                        }
1566                        if (!connectToService()) {
1567                            Slog.e(TAG, "Failed to bind to media container service");
1568                            for (HandlerParams params : mPendingInstalls) {
1569                                // Indicate service bind error
1570                                params.serviceError();
1571                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1572                                        System.identityHashCode(params));
1573                            }
1574                            mPendingInstalls.clear();
1575                        }
1576                    }
1577                    break;
1578                }
1579                case MCS_UNBIND: {
1580                    // If there is no actual work left, then time to unbind.
1581                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1582
1583                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1584                        if (mBound) {
1585                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1586
1587                            disconnectService();
1588                        }
1589                    } else if (mPendingInstalls.size() > 0) {
1590                        // There are more pending requests in queue.
1591                        // Just post MCS_BOUND message to trigger processing
1592                        // of next pending install.
1593                        mHandler.sendEmptyMessage(MCS_BOUND);
1594                    }
1595
1596                    break;
1597                }
1598                case MCS_GIVE_UP: {
1599                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1600                    HandlerParams params = mPendingInstalls.remove(0);
1601                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1602                            System.identityHashCode(params));
1603                    break;
1604                }
1605                case SEND_PENDING_BROADCAST: {
1606                    String packages[];
1607                    ArrayList<String> components[];
1608                    int size = 0;
1609                    int uids[];
1610                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1611                    synchronized (mPackages) {
1612                        if (mPendingBroadcasts == null) {
1613                            return;
1614                        }
1615                        size = mPendingBroadcasts.size();
1616                        if (size <= 0) {
1617                            // Nothing to be done. Just return
1618                            return;
1619                        }
1620                        packages = new String[size];
1621                        components = new ArrayList[size];
1622                        uids = new int[size];
1623                        int i = 0;  // filling out the above arrays
1624
1625                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1626                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1627                            Iterator<Map.Entry<String, ArrayList<String>>> it
1628                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1629                                            .entrySet().iterator();
1630                            while (it.hasNext() && i < size) {
1631                                Map.Entry<String, ArrayList<String>> ent = it.next();
1632                                packages[i] = ent.getKey();
1633                                components[i] = ent.getValue();
1634                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1635                                uids[i] = (ps != null)
1636                                        ? UserHandle.getUid(packageUserId, ps.appId)
1637                                        : -1;
1638                                i++;
1639                            }
1640                        }
1641                        size = i;
1642                        mPendingBroadcasts.clear();
1643                    }
1644                    // Send broadcasts
1645                    for (int i = 0; i < size; i++) {
1646                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1647                    }
1648                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1649                    break;
1650                }
1651                case START_CLEANING_PACKAGE: {
1652                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1653                    final String packageName = (String)msg.obj;
1654                    final int userId = msg.arg1;
1655                    final boolean andCode = msg.arg2 != 0;
1656                    synchronized (mPackages) {
1657                        if (userId == UserHandle.USER_ALL) {
1658                            int[] users = sUserManager.getUserIds();
1659                            for (int user : users) {
1660                                mSettings.addPackageToCleanLPw(
1661                                        new PackageCleanItem(user, packageName, andCode));
1662                            }
1663                        } else {
1664                            mSettings.addPackageToCleanLPw(
1665                                    new PackageCleanItem(userId, packageName, andCode));
1666                        }
1667                    }
1668                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1669                    startCleaningPackages();
1670                } break;
1671                case POST_INSTALL: {
1672                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1673
1674                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1675                    final boolean didRestore = (msg.arg2 != 0);
1676                    mRunningInstalls.delete(msg.arg1);
1677
1678                    if (data != null) {
1679                        InstallArgs args = data.args;
1680                        PackageInstalledInfo parentRes = data.res;
1681
1682                        final boolean grantPermissions = (args.installFlags
1683                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1684                        final boolean killApp = (args.installFlags
1685                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1686                        final boolean virtualPreload = ((args.installFlags
1687                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1688                        final String[] grantedPermissions = args.installGrantPermissions;
1689
1690                        // Handle the parent package
1691                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1692                                virtualPreload, grantedPermissions, didRestore,
1693                                args.installerPackageName, args.observer);
1694
1695                        // Handle the child packages
1696                        final int childCount = (parentRes.addedChildPackages != null)
1697                                ? parentRes.addedChildPackages.size() : 0;
1698                        for (int i = 0; i < childCount; i++) {
1699                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1700                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1701                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1702                                    args.installerPackageName, args.observer);
1703                        }
1704
1705                        // Log tracing if needed
1706                        if (args.traceMethod != null) {
1707                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1708                                    args.traceCookie);
1709                        }
1710                    } else {
1711                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1712                    }
1713
1714                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1715                } break;
1716                case UPDATED_MEDIA_STATUS: {
1717                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1718                    boolean reportStatus = msg.arg1 == 1;
1719                    boolean doGc = msg.arg2 == 1;
1720                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1721                    if (doGc) {
1722                        // Force a gc to clear up stale containers.
1723                        Runtime.getRuntime().gc();
1724                    }
1725                    if (msg.obj != null) {
1726                        @SuppressWarnings("unchecked")
1727                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1728                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1729                        // Unload containers
1730                        unloadAllContainers(args);
1731                    }
1732                    if (reportStatus) {
1733                        try {
1734                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1735                                    "Invoking StorageManagerService call back");
1736                            PackageHelper.getStorageManager().finishMediaUpdate();
1737                        } catch (RemoteException e) {
1738                            Log.e(TAG, "StorageManagerService not running?");
1739                        }
1740                    }
1741                } break;
1742                case WRITE_SETTINGS: {
1743                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1744                    synchronized (mPackages) {
1745                        removeMessages(WRITE_SETTINGS);
1746                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1747                        mSettings.writeLPr();
1748                        mDirtyUsers.clear();
1749                    }
1750                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1751                } break;
1752                case WRITE_PACKAGE_RESTRICTIONS: {
1753                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1754                    synchronized (mPackages) {
1755                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1756                        for (int userId : mDirtyUsers) {
1757                            mSettings.writePackageRestrictionsLPr(userId);
1758                        }
1759                        mDirtyUsers.clear();
1760                    }
1761                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1762                } break;
1763                case WRITE_PACKAGE_LIST: {
1764                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1765                    synchronized (mPackages) {
1766                        removeMessages(WRITE_PACKAGE_LIST);
1767                        mSettings.writePackageListLPr(msg.arg1);
1768                    }
1769                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1770                } break;
1771                case CHECK_PENDING_VERIFICATION: {
1772                    final int verificationId = msg.arg1;
1773                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1774
1775                    if ((state != null) && !state.timeoutExtended()) {
1776                        final InstallArgs args = state.getInstallArgs();
1777                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1778
1779                        Slog.i(TAG, "Verification timed out for " + originUri);
1780                        mPendingVerification.remove(verificationId);
1781
1782                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1783
1784                        final UserHandle user = args.getUser();
1785                        if (getDefaultVerificationResponse(user)
1786                                == PackageManager.VERIFICATION_ALLOW) {
1787                            Slog.i(TAG, "Continuing with installation of " + originUri);
1788                            state.setVerifierResponse(Binder.getCallingUid(),
1789                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1790                            broadcastPackageVerified(verificationId, originUri,
1791                                    PackageManager.VERIFICATION_ALLOW, user);
1792                            try {
1793                                ret = args.copyApk(mContainerService, true);
1794                            } catch (RemoteException e) {
1795                                Slog.e(TAG, "Could not contact the ContainerService");
1796                            }
1797                        } else {
1798                            broadcastPackageVerified(verificationId, originUri,
1799                                    PackageManager.VERIFICATION_REJECT, user);
1800                        }
1801
1802                        Trace.asyncTraceEnd(
1803                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1804
1805                        processPendingInstall(args, ret);
1806                        mHandler.sendEmptyMessage(MCS_UNBIND);
1807                    }
1808                    break;
1809                }
1810                case PACKAGE_VERIFIED: {
1811                    final int verificationId = msg.arg1;
1812
1813                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1814                    if (state == null) {
1815                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1816                        break;
1817                    }
1818
1819                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1820
1821                    state.setVerifierResponse(response.callerUid, response.code);
1822
1823                    if (state.isVerificationComplete()) {
1824                        mPendingVerification.remove(verificationId);
1825
1826                        final InstallArgs args = state.getInstallArgs();
1827                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1828
1829                        int ret;
1830                        if (state.isInstallAllowed()) {
1831                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1832                            broadcastPackageVerified(verificationId, originUri,
1833                                    response.code, state.getInstallArgs().getUser());
1834                            try {
1835                                ret = args.copyApk(mContainerService, true);
1836                            } catch (RemoteException e) {
1837                                Slog.e(TAG, "Could not contact the ContainerService");
1838                            }
1839                        } else {
1840                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1841                        }
1842
1843                        Trace.asyncTraceEnd(
1844                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1845
1846                        processPendingInstall(args, ret);
1847                        mHandler.sendEmptyMessage(MCS_UNBIND);
1848                    }
1849
1850                    break;
1851                }
1852                case START_INTENT_FILTER_VERIFICATIONS: {
1853                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1854                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1855                            params.replacing, params.pkg);
1856                    break;
1857                }
1858                case INTENT_FILTER_VERIFIED: {
1859                    final int verificationId = msg.arg1;
1860
1861                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1862                            verificationId);
1863                    if (state == null) {
1864                        Slog.w(TAG, "Invalid IntentFilter verification token "
1865                                + verificationId + " received");
1866                        break;
1867                    }
1868
1869                    final int userId = state.getUserId();
1870
1871                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1872                            "Processing IntentFilter verification with token:"
1873                            + verificationId + " and userId:" + userId);
1874
1875                    final IntentFilterVerificationResponse response =
1876                            (IntentFilterVerificationResponse) msg.obj;
1877
1878                    state.setVerifierResponse(response.callerUid, response.code);
1879
1880                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1881                            "IntentFilter verification with token:" + verificationId
1882                            + " and userId:" + userId
1883                            + " is settings verifier response with response code:"
1884                            + response.code);
1885
1886                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1887                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1888                                + response.getFailedDomainsString());
1889                    }
1890
1891                    if (state.isVerificationComplete()) {
1892                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1893                    } else {
1894                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1895                                "IntentFilter verification with token:" + verificationId
1896                                + " was not said to be complete");
1897                    }
1898
1899                    break;
1900                }
1901                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1902                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1903                            mInstantAppResolverConnection,
1904                            (InstantAppRequest) msg.obj,
1905                            mInstantAppInstallerActivity,
1906                            mHandler);
1907                }
1908            }
1909        }
1910    }
1911
1912    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1913            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1914            boolean launchedForRestore, String installerPackage,
1915            IPackageInstallObserver2 installObserver) {
1916        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1917            // Send the removed broadcasts
1918            if (res.removedInfo != null) {
1919                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1920            }
1921
1922            // Now that we successfully installed the package, grant runtime
1923            // permissions if requested before broadcasting the install. Also
1924            // for legacy apps in permission review mode we clear the permission
1925            // review flag which is used to emulate runtime permissions for
1926            // legacy apps.
1927            if (grantPermissions) {
1928                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1929            }
1930
1931            final boolean update = res.removedInfo != null
1932                    && res.removedInfo.removedPackage != null;
1933            final String installerPackageName =
1934                    res.installerPackageName != null
1935                            ? res.installerPackageName
1936                            : res.removedInfo != null
1937                                    ? res.removedInfo.installerPackageName
1938                                    : null;
1939
1940            // If this is the first time we have child packages for a disabled privileged
1941            // app that had no children, we grant requested runtime permissions to the new
1942            // children if the parent on the system image had them already granted.
1943            if (res.pkg.parentPackage != null) {
1944                synchronized (mPackages) {
1945                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1946                }
1947            }
1948
1949            synchronized (mPackages) {
1950                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1951            }
1952
1953            final String packageName = res.pkg.applicationInfo.packageName;
1954
1955            // Determine the set of users who are adding this package for
1956            // the first time vs. those who are seeing an update.
1957            int[] firstUsers = EMPTY_INT_ARRAY;
1958            int[] updateUsers = EMPTY_INT_ARRAY;
1959            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1960            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1961            for (int newUser : res.newUsers) {
1962                if (ps.getInstantApp(newUser)) {
1963                    continue;
1964                }
1965                if (allNewUsers) {
1966                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1967                    continue;
1968                }
1969                boolean isNew = true;
1970                for (int origUser : res.origUsers) {
1971                    if (origUser == newUser) {
1972                        isNew = false;
1973                        break;
1974                    }
1975                }
1976                if (isNew) {
1977                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1978                } else {
1979                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1980                }
1981            }
1982
1983            // Send installed broadcasts if the package is not a static shared lib.
1984            if (res.pkg.staticSharedLibName == null) {
1985                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1986
1987                // Send added for users that see the package for the first time
1988                // sendPackageAddedForNewUsers also deals with system apps
1989                int appId = UserHandle.getAppId(res.uid);
1990                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1991                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1992                        virtualPreload /*startReceiver*/, appId, firstUsers);
1993
1994                // Send added for users that don't see the package for the first time
1995                Bundle extras = new Bundle(1);
1996                extras.putInt(Intent.EXTRA_UID, res.uid);
1997                if (update) {
1998                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1999                }
2000                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2001                        extras, 0 /*flags*/,
2002                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2003                if (installerPackageName != null) {
2004                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2005                            extras, 0 /*flags*/,
2006                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2007                }
2008
2009                // Send replaced for users that don't see the package for the first time
2010                if (update) {
2011                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2012                            packageName, extras, 0 /*flags*/,
2013                            null /*targetPackage*/, null /*finishedReceiver*/,
2014                            updateUsers);
2015                    if (installerPackageName != null) {
2016                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2017                                extras, 0 /*flags*/,
2018                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2019                    }
2020                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2021                            null /*package*/, null /*extras*/, 0 /*flags*/,
2022                            packageName /*targetPackage*/,
2023                            null /*finishedReceiver*/, updateUsers);
2024                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2025                    // First-install and we did a restore, so we're responsible for the
2026                    // first-launch broadcast.
2027                    if (DEBUG_BACKUP) {
2028                        Slog.i(TAG, "Post-restore of " + packageName
2029                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2030                    }
2031                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2032                }
2033
2034                // Send broadcast package appeared if forward locked/external for all users
2035                // treat asec-hosted packages like removable media on upgrade
2036                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2037                    if (DEBUG_INSTALL) {
2038                        Slog.i(TAG, "upgrading pkg " + res.pkg
2039                                + " is ASEC-hosted -> AVAILABLE");
2040                    }
2041                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2042                    ArrayList<String> pkgList = new ArrayList<>(1);
2043                    pkgList.add(packageName);
2044                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2045                }
2046            }
2047
2048            // Work that needs to happen on first install within each user
2049            if (firstUsers != null && firstUsers.length > 0) {
2050                synchronized (mPackages) {
2051                    for (int userId : firstUsers) {
2052                        // If this app is a browser and it's newly-installed for some
2053                        // users, clear any default-browser state in those users. The
2054                        // app's nature doesn't depend on the user, so we can just check
2055                        // its browser nature in any user and generalize.
2056                        if (packageIsBrowser(packageName, userId)) {
2057                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2058                        }
2059
2060                        // We may also need to apply pending (restored) runtime
2061                        // permission grants within these users.
2062                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2063                    }
2064                }
2065            }
2066
2067            // Log current value of "unknown sources" setting
2068            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2069                    getUnknownSourcesSettings());
2070
2071            // Remove the replaced package's older resources safely now
2072            // We delete after a gc for applications  on sdcard.
2073            if (res.removedInfo != null && res.removedInfo.args != null) {
2074                Runtime.getRuntime().gc();
2075                synchronized (mInstallLock) {
2076                    res.removedInfo.args.doPostDeleteLI(true);
2077                }
2078            } else {
2079                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2080                // and not block here.
2081                VMRuntime.getRuntime().requestConcurrentGC();
2082            }
2083
2084            // Notify DexManager that the package was installed for new users.
2085            // The updated users should already be indexed and the package code paths
2086            // should not change.
2087            // Don't notify the manager for ephemeral apps as they are not expected to
2088            // survive long enough to benefit of background optimizations.
2089            for (int userId : firstUsers) {
2090                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2091                // There's a race currently where some install events may interleave with an uninstall.
2092                // This can lead to package info being null (b/36642664).
2093                if (info != null) {
2094                    mDexManager.notifyPackageInstalled(info, userId);
2095                }
2096            }
2097        }
2098
2099        // If someone is watching installs - notify them
2100        if (installObserver != null) {
2101            try {
2102                Bundle extras = extrasForInstallResult(res);
2103                installObserver.onPackageInstalled(res.name, res.returnCode,
2104                        res.returnMsg, extras);
2105            } catch (RemoteException e) {
2106                Slog.i(TAG, "Observer no longer exists.");
2107            }
2108        }
2109    }
2110
2111    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2112            PackageParser.Package pkg) {
2113        if (pkg.parentPackage == null) {
2114            return;
2115        }
2116        if (pkg.requestedPermissions == null) {
2117            return;
2118        }
2119        final PackageSetting disabledSysParentPs = mSettings
2120                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2121        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2122                || !disabledSysParentPs.isPrivileged()
2123                || (disabledSysParentPs.childPackageNames != null
2124                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2125            return;
2126        }
2127        final int[] allUserIds = sUserManager.getUserIds();
2128        final int permCount = pkg.requestedPermissions.size();
2129        for (int i = 0; i < permCount; i++) {
2130            String permission = pkg.requestedPermissions.get(i);
2131            BasePermission bp = mSettings.mPermissions.get(permission);
2132            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2133                continue;
2134            }
2135            for (int userId : allUserIds) {
2136                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2137                        permission, userId)) {
2138                    grantRuntimePermission(pkg.packageName, permission, userId);
2139                }
2140            }
2141        }
2142    }
2143
2144    private StorageEventListener mStorageListener = new StorageEventListener() {
2145        @Override
2146        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2147            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2148                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2149                    final String volumeUuid = vol.getFsUuid();
2150
2151                    // Clean up any users or apps that were removed or recreated
2152                    // while this volume was missing
2153                    sUserManager.reconcileUsers(volumeUuid);
2154                    reconcileApps(volumeUuid);
2155
2156                    // Clean up any install sessions that expired or were
2157                    // cancelled while this volume was missing
2158                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2159
2160                    loadPrivatePackages(vol);
2161
2162                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2163                    unloadPrivatePackages(vol);
2164                }
2165            }
2166
2167            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2168                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2169                    updateExternalMediaStatus(true, false);
2170                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2171                    updateExternalMediaStatus(false, false);
2172                }
2173            }
2174        }
2175
2176        @Override
2177        public void onVolumeForgotten(String fsUuid) {
2178            if (TextUtils.isEmpty(fsUuid)) {
2179                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2180                return;
2181            }
2182
2183            // Remove any apps installed on the forgotten volume
2184            synchronized (mPackages) {
2185                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2186                for (PackageSetting ps : packages) {
2187                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2188                    deletePackageVersioned(new VersionedPackage(ps.name,
2189                            PackageManager.VERSION_CODE_HIGHEST),
2190                            new LegacyPackageDeleteObserver(null).getBinder(),
2191                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2192                    // Try very hard to release any references to this package
2193                    // so we don't risk the system server being killed due to
2194                    // open FDs
2195                    AttributeCache.instance().removePackage(ps.name);
2196                }
2197
2198                mSettings.onVolumeForgotten(fsUuid);
2199                mSettings.writeLPr();
2200            }
2201        }
2202    };
2203
2204    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2205            String[] grantedPermissions) {
2206        for (int userId : userIds) {
2207            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2208        }
2209    }
2210
2211    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2212            String[] grantedPermissions) {
2213        PackageSetting ps = (PackageSetting) pkg.mExtras;
2214        if (ps == null) {
2215            return;
2216        }
2217
2218        PermissionsState permissionsState = ps.getPermissionsState();
2219
2220        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2221                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2222
2223        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2224                >= Build.VERSION_CODES.M;
2225
2226        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2227
2228        for (String permission : pkg.requestedPermissions) {
2229            final BasePermission bp;
2230            synchronized (mPackages) {
2231                bp = mSettings.mPermissions.get(permission);
2232            }
2233            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2234                    && (!instantApp || bp.isInstant())
2235                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2236                    && (grantedPermissions == null
2237                           || ArrayUtils.contains(grantedPermissions, permission))) {
2238                final int flags = permissionsState.getPermissionFlags(permission, userId);
2239                if (supportsRuntimePermissions) {
2240                    // Installer cannot change immutable permissions.
2241                    if ((flags & immutableFlags) == 0) {
2242                        grantRuntimePermission(pkg.packageName, permission, userId);
2243                    }
2244                } else if (mPermissionReviewRequired) {
2245                    // In permission review mode we clear the review flag when we
2246                    // are asked to install the app with all permissions granted.
2247                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2248                        updatePermissionFlags(permission, pkg.packageName,
2249                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2250                    }
2251                }
2252            }
2253        }
2254    }
2255
2256    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2257        Bundle extras = null;
2258        switch (res.returnCode) {
2259            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2260                extras = new Bundle();
2261                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2262                        res.origPermission);
2263                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2264                        res.origPackage);
2265                break;
2266            }
2267            case PackageManager.INSTALL_SUCCEEDED: {
2268                extras = new Bundle();
2269                extras.putBoolean(Intent.EXTRA_REPLACING,
2270                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2271                break;
2272            }
2273        }
2274        return extras;
2275    }
2276
2277    void scheduleWriteSettingsLocked() {
2278        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2279            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2280        }
2281    }
2282
2283    void scheduleWritePackageListLocked(int userId) {
2284        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2285            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2286            msg.arg1 = userId;
2287            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2288        }
2289    }
2290
2291    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2292        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2293        scheduleWritePackageRestrictionsLocked(userId);
2294    }
2295
2296    void scheduleWritePackageRestrictionsLocked(int userId) {
2297        final int[] userIds = (userId == UserHandle.USER_ALL)
2298                ? sUserManager.getUserIds() : new int[]{userId};
2299        for (int nextUserId : userIds) {
2300            if (!sUserManager.exists(nextUserId)) return;
2301            mDirtyUsers.add(nextUserId);
2302            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2303                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2304            }
2305        }
2306    }
2307
2308    public static PackageManagerService main(Context context, Installer installer,
2309            boolean factoryTest, boolean onlyCore) {
2310        // Self-check for initial settings.
2311        PackageManagerServiceCompilerMapping.checkProperties();
2312
2313        PackageManagerService m = new PackageManagerService(context, installer,
2314                factoryTest, onlyCore);
2315        m.enableSystemUserPackages();
2316        ServiceManager.addService("package", m);
2317        final PackageManagerNative pmn = m.new PackageManagerNative();
2318        ServiceManager.addService("package_native", pmn);
2319        return m;
2320    }
2321
2322    private void enableSystemUserPackages() {
2323        if (!UserManager.isSplitSystemUser()) {
2324            return;
2325        }
2326        // For system user, enable apps based on the following conditions:
2327        // - app is whitelisted or belong to one of these groups:
2328        //   -- system app which has no launcher icons
2329        //   -- system app which has INTERACT_ACROSS_USERS permission
2330        //   -- system IME app
2331        // - app is not in the blacklist
2332        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2333        Set<String> enableApps = new ArraySet<>();
2334        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2335                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2336                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2337        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2338        enableApps.addAll(wlApps);
2339        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2340                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2341        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2342        enableApps.removeAll(blApps);
2343        Log.i(TAG, "Applications installed for system user: " + enableApps);
2344        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2345                UserHandle.SYSTEM);
2346        final int allAppsSize = allAps.size();
2347        synchronized (mPackages) {
2348            for (int i = 0; i < allAppsSize; i++) {
2349                String pName = allAps.get(i);
2350                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2351                // Should not happen, but we shouldn't be failing if it does
2352                if (pkgSetting == null) {
2353                    continue;
2354                }
2355                boolean install = enableApps.contains(pName);
2356                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2357                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2358                            + " for system user");
2359                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2360                }
2361            }
2362            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2363        }
2364    }
2365
2366    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2367        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2368                Context.DISPLAY_SERVICE);
2369        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2370    }
2371
2372    /**
2373     * Requests that files preopted on a secondary system partition be copied to the data partition
2374     * if possible.  Note that the actual copying of the files is accomplished by init for security
2375     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2376     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2377     */
2378    private static void requestCopyPreoptedFiles() {
2379        final int WAIT_TIME_MS = 100;
2380        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2381        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2382            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2383            // We will wait for up to 100 seconds.
2384            final long timeStart = SystemClock.uptimeMillis();
2385            final long timeEnd = timeStart + 100 * 1000;
2386            long timeNow = timeStart;
2387            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2388                try {
2389                    Thread.sleep(WAIT_TIME_MS);
2390                } catch (InterruptedException e) {
2391                    // Do nothing
2392                }
2393                timeNow = SystemClock.uptimeMillis();
2394                if (timeNow > timeEnd) {
2395                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2396                    Slog.wtf(TAG, "cppreopt did not finish!");
2397                    break;
2398                }
2399            }
2400
2401            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2402        }
2403    }
2404
2405    public PackageManagerService(Context context, Installer installer,
2406            boolean factoryTest, boolean onlyCore) {
2407        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2408        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2409        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2410                SystemClock.uptimeMillis());
2411
2412        if (mSdkVersion <= 0) {
2413            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2414        }
2415
2416        mContext = context;
2417
2418        mPermissionReviewRequired = context.getResources().getBoolean(
2419                R.bool.config_permissionReviewRequired);
2420
2421        mFactoryTest = factoryTest;
2422        mOnlyCore = onlyCore;
2423        mMetrics = new DisplayMetrics();
2424        mSettings = new Settings(mPackages);
2425        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2426                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2427        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2430                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2432                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2433        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2434                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2435        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2436                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2437
2438        String separateProcesses = SystemProperties.get("debug.separate_processes");
2439        if (separateProcesses != null && separateProcesses.length() > 0) {
2440            if ("*".equals(separateProcesses)) {
2441                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2442                mSeparateProcesses = null;
2443                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2444            } else {
2445                mDefParseFlags = 0;
2446                mSeparateProcesses = separateProcesses.split(",");
2447                Slog.w(TAG, "Running with debug.separate_processes: "
2448                        + separateProcesses);
2449            }
2450        } else {
2451            mDefParseFlags = 0;
2452            mSeparateProcesses = null;
2453        }
2454
2455        mInstaller = installer;
2456        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2457                "*dexopt*");
2458        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2459        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2460
2461        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2462                FgThread.get().getLooper());
2463
2464        getDefaultDisplayMetrics(context, mMetrics);
2465
2466        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2467        SystemConfig systemConfig = SystemConfig.getInstance();
2468        mGlobalGids = systemConfig.getGlobalGids();
2469        mSystemPermissions = systemConfig.getSystemPermissions();
2470        mAvailableFeatures = systemConfig.getAvailableFeatures();
2471        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2472
2473        mProtectedPackages = new ProtectedPackages(mContext);
2474
2475        synchronized (mInstallLock) {
2476        // writer
2477        synchronized (mPackages) {
2478            mHandlerThread = new ServiceThread(TAG,
2479                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2480            mHandlerThread.start();
2481            mHandler = new PackageHandler(mHandlerThread.getLooper());
2482            mProcessLoggingHandler = new ProcessLoggingHandler();
2483            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2484
2485            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2486            mInstantAppRegistry = new InstantAppRegistry(this);
2487
2488            File dataDir = Environment.getDataDirectory();
2489            mAppInstallDir = new File(dataDir, "app");
2490            mAppLib32InstallDir = new File(dataDir, "app-lib");
2491            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2492            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2493            sUserManager = new UserManagerService(context, this,
2494                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2495
2496            // Propagate permission configuration in to package manager.
2497            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2498                    = systemConfig.getPermissions();
2499            for (int i=0; i<permConfig.size(); i++) {
2500                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2501                BasePermission bp = mSettings.mPermissions.get(perm.name);
2502                if (bp == null) {
2503                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2504                    mSettings.mPermissions.put(perm.name, bp);
2505                }
2506                if (perm.gids != null) {
2507                    bp.setGids(perm.gids, perm.perUser);
2508                }
2509            }
2510
2511            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2512            final int builtInLibCount = libConfig.size();
2513            for (int i = 0; i < builtInLibCount; i++) {
2514                String name = libConfig.keyAt(i);
2515                String path = libConfig.valueAt(i);
2516                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2517                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2518            }
2519
2520            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2521
2522            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2523            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2524            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2525
2526            // Clean up orphaned packages for which the code path doesn't exist
2527            // and they are an update to a system app - caused by bug/32321269
2528            final int packageSettingCount = mSettings.mPackages.size();
2529            for (int i = packageSettingCount - 1; i >= 0; i--) {
2530                PackageSetting ps = mSettings.mPackages.valueAt(i);
2531                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2532                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2533                    mSettings.mPackages.removeAt(i);
2534                    mSettings.enableSystemPackageLPw(ps.name);
2535                }
2536            }
2537
2538            if (mFirstBoot) {
2539                requestCopyPreoptedFiles();
2540            }
2541
2542            String customResolverActivity = Resources.getSystem().getString(
2543                    R.string.config_customResolverActivity);
2544            if (TextUtils.isEmpty(customResolverActivity)) {
2545                customResolverActivity = null;
2546            } else {
2547                mCustomResolverComponentName = ComponentName.unflattenFromString(
2548                        customResolverActivity);
2549            }
2550
2551            long startTime = SystemClock.uptimeMillis();
2552
2553            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2554                    startTime);
2555
2556            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2557            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2558
2559            if (bootClassPath == null) {
2560                Slog.w(TAG, "No BOOTCLASSPATH found!");
2561            }
2562
2563            if (systemServerClassPath == null) {
2564                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2565            }
2566
2567            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2568
2569            final VersionInfo ver = mSettings.getInternalVersion();
2570            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2571            if (mIsUpgrade) {
2572                logCriticalInfo(Log.INFO,
2573                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2574            }
2575
2576            // when upgrading from pre-M, promote system app permissions from install to runtime
2577            mPromoteSystemApps =
2578                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2579
2580            // When upgrading from pre-N, we need to handle package extraction like first boot,
2581            // as there is no profiling data available.
2582            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2583
2584            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2585
2586            // save off the names of pre-existing system packages prior to scanning; we don't
2587            // want to automatically grant runtime permissions for new system apps
2588            if (mPromoteSystemApps) {
2589                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2590                while (pkgSettingIter.hasNext()) {
2591                    PackageSetting ps = pkgSettingIter.next();
2592                    if (isSystemApp(ps)) {
2593                        mExistingSystemPackages.add(ps.name);
2594                    }
2595                }
2596            }
2597
2598            mCacheDir = preparePackageParserCache(mIsUpgrade);
2599
2600            // Set flag to monitor and not change apk file paths when
2601            // scanning install directories.
2602            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2603
2604            if (mIsUpgrade || mFirstBoot) {
2605                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2606            }
2607
2608            // Collect vendor overlay packages. (Do this before scanning any apps.)
2609            // For security and version matching reason, only consider
2610            // overlay packages if they reside in the right directory.
2611            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2612                    | PackageParser.PARSE_IS_SYSTEM
2613                    | PackageParser.PARSE_IS_SYSTEM_DIR
2614                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2615
2616            mParallelPackageParserCallback.findStaticOverlayPackages();
2617
2618            // Find base frameworks (resource packages without code).
2619            scanDirTracedLI(frameworkDir, mDefParseFlags
2620                    | PackageParser.PARSE_IS_SYSTEM
2621                    | PackageParser.PARSE_IS_SYSTEM_DIR
2622                    | PackageParser.PARSE_IS_PRIVILEGED,
2623                    scanFlags | SCAN_NO_DEX, 0);
2624
2625            // Collected privileged system packages.
2626            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2627            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2628                    | PackageParser.PARSE_IS_SYSTEM
2629                    | PackageParser.PARSE_IS_SYSTEM_DIR
2630                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2631
2632            // Collect ordinary system packages.
2633            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2634            scanDirTracedLI(systemAppDir, mDefParseFlags
2635                    | PackageParser.PARSE_IS_SYSTEM
2636                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2637
2638            // Collect all vendor packages.
2639            File vendorAppDir = new File("/vendor/app");
2640            try {
2641                vendorAppDir = vendorAppDir.getCanonicalFile();
2642            } catch (IOException e) {
2643                // failed to look up canonical path, continue with original one
2644            }
2645            scanDirTracedLI(vendorAppDir, mDefParseFlags
2646                    | PackageParser.PARSE_IS_SYSTEM
2647                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2648
2649            // Collect all OEM packages.
2650            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2651            scanDirTracedLI(oemAppDir, mDefParseFlags
2652                    | PackageParser.PARSE_IS_SYSTEM
2653                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2654
2655            // Prune any system packages that no longer exist.
2656            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2657            // Stub packages must either be replaced with full versions in the /data
2658            // partition or be disabled.
2659            final List<String> stubSystemApps = new ArrayList<>();
2660            if (!mOnlyCore) {
2661                // do this first before mucking with mPackages for the "expecting better" case
2662                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2663                while (pkgIterator.hasNext()) {
2664                    final PackageParser.Package pkg = pkgIterator.next();
2665                    if (pkg.isStub) {
2666                        stubSystemApps.add(pkg.packageName);
2667                    }
2668                }
2669
2670                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2671                while (psit.hasNext()) {
2672                    PackageSetting ps = psit.next();
2673
2674                    /*
2675                     * If this is not a system app, it can't be a
2676                     * disable system app.
2677                     */
2678                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2679                        continue;
2680                    }
2681
2682                    /*
2683                     * If the package is scanned, it's not erased.
2684                     */
2685                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2686                    if (scannedPkg != null) {
2687                        /*
2688                         * If the system app is both scanned and in the
2689                         * disabled packages list, then it must have been
2690                         * added via OTA. Remove it from the currently
2691                         * scanned package so the previously user-installed
2692                         * application can be scanned.
2693                         */
2694                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2695                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2696                                    + ps.name + "; removing system app.  Last known codePath="
2697                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2698                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2699                                    + scannedPkg.mVersionCode);
2700                            removePackageLI(scannedPkg, true);
2701                            mExpectingBetter.put(ps.name, ps.codePath);
2702                        }
2703
2704                        continue;
2705                    }
2706
2707                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2708                        psit.remove();
2709                        logCriticalInfo(Log.WARN, "System package " + ps.name
2710                                + " no longer exists; it's data will be wiped");
2711                        // Actual deletion of code and data will be handled by later
2712                        // reconciliation step
2713                    } else {
2714                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2715                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2716                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2717                        }
2718                    }
2719                }
2720            }
2721
2722            //look for any incomplete package installations
2723            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2724            for (int i = 0; i < deletePkgsList.size(); i++) {
2725                // Actual deletion of code and data will be handled by later
2726                // reconciliation step
2727                final String packageName = deletePkgsList.get(i).name;
2728                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2729                synchronized (mPackages) {
2730                    mSettings.removePackageLPw(packageName);
2731                }
2732            }
2733
2734            //delete tmp files
2735            deleteTempPackageFiles();
2736
2737            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2738
2739            // Remove any shared userIDs that have no associated packages
2740            mSettings.pruneSharedUsersLPw();
2741            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2742            final int systemPackagesCount = mPackages.size();
2743            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2744                    + " ms, packageCount: " + systemPackagesCount
2745                    + " , timePerPackage: "
2746                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2747                    + " , cached: " + cachedSystemApps);
2748            if (mIsUpgrade && systemPackagesCount > 0) {
2749                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2750                        ((int) systemScanTime) / systemPackagesCount);
2751            }
2752            if (!mOnlyCore) {
2753                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2754                        SystemClock.uptimeMillis());
2755                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2756
2757                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2758                        | PackageParser.PARSE_FORWARD_LOCK,
2759                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2760
2761                // Remove disable package settings for updated system apps that were
2762                // removed via an OTA. If the update is no longer present, remove the
2763                // app completely. Otherwise, revoke their system privileges.
2764                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2765                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2766                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2767
2768                    final String msg;
2769                    if (deletedPkg == null) {
2770                        // should have found an update, but, we didn't; remove everything
2771                        msg = "Updated system package " + deletedAppName
2772                                + " no longer exists; removing its data";
2773                        // Actual deletion of code and data will be handled by later
2774                        // reconciliation step
2775                    } else {
2776                        // found an update; revoke system privileges
2777                        msg = "Updated system package + " + deletedAppName
2778                                + " no longer exists; revoking system privileges";
2779
2780                        // Don't do anything if a stub is removed from the system image. If
2781                        // we were to remove the uncompressed version from the /data partition,
2782                        // this is where it'd be done.
2783
2784                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2785                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2786                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2787                    }
2788                    logCriticalInfo(Log.WARN, msg);
2789                }
2790
2791                /*
2792                 * Make sure all system apps that we expected to appear on
2793                 * the userdata partition actually showed up. If they never
2794                 * appeared, crawl back and revive the system version.
2795                 */
2796                for (int i = 0; i < mExpectingBetter.size(); i++) {
2797                    final String packageName = mExpectingBetter.keyAt(i);
2798                    if (!mPackages.containsKey(packageName)) {
2799                        final File scanFile = mExpectingBetter.valueAt(i);
2800
2801                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2802                                + " but never showed up; reverting to system");
2803
2804                        int reparseFlags = mDefParseFlags;
2805                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2806                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2807                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2808                                    | PackageParser.PARSE_IS_PRIVILEGED;
2809                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2810                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2811                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2812                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2813                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2814                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2815                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2816                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2817                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2818                        } else {
2819                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2820                            continue;
2821                        }
2822
2823                        mSettings.enableSystemPackageLPw(packageName);
2824
2825                        try {
2826                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2827                        } catch (PackageManagerException e) {
2828                            Slog.e(TAG, "Failed to parse original system package: "
2829                                    + e.getMessage());
2830                        }
2831                    }
2832                }
2833
2834                // Uncompress and install any stubbed system applications.
2835                // This must be done last to ensure all stubs are replaced or disabled.
2836                decompressSystemApplications(stubSystemApps, scanFlags);
2837
2838                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2839                                - cachedSystemApps;
2840
2841                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2842                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2843                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2844                        + " ms, packageCount: " + dataPackagesCount
2845                        + " , timePerPackage: "
2846                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2847                        + " , cached: " + cachedNonSystemApps);
2848                if (mIsUpgrade && dataPackagesCount > 0) {
2849                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2850                            ((int) dataScanTime) / dataPackagesCount);
2851                }
2852            }
2853            mExpectingBetter.clear();
2854
2855            // Resolve the storage manager.
2856            mStorageManagerPackage = getStorageManagerPackageName();
2857
2858            // Resolve protected action filters. Only the setup wizard is allowed to
2859            // have a high priority filter for these actions.
2860            mSetupWizardPackage = getSetupWizardPackageName();
2861            if (mProtectedFilters.size() > 0) {
2862                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2863                    Slog.i(TAG, "No setup wizard;"
2864                        + " All protected intents capped to priority 0");
2865                }
2866                for (ActivityIntentInfo filter : mProtectedFilters) {
2867                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2868                        if (DEBUG_FILTERS) {
2869                            Slog.i(TAG, "Found setup wizard;"
2870                                + " allow priority " + filter.getPriority() + ";"
2871                                + " package: " + filter.activity.info.packageName
2872                                + " activity: " + filter.activity.className
2873                                + " priority: " + filter.getPriority());
2874                        }
2875                        // skip setup wizard; allow it to keep the high priority filter
2876                        continue;
2877                    }
2878                    if (DEBUG_FILTERS) {
2879                        Slog.i(TAG, "Protected action; cap priority to 0;"
2880                                + " package: " + filter.activity.info.packageName
2881                                + " activity: " + filter.activity.className
2882                                + " origPrio: " + filter.getPriority());
2883                    }
2884                    filter.setPriority(0);
2885                }
2886            }
2887            mDeferProtectedFilters = false;
2888            mProtectedFilters.clear();
2889
2890            // Now that we know all of the shared libraries, update all clients to have
2891            // the correct library paths.
2892            updateAllSharedLibrariesLPw(null);
2893
2894            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2895                // NOTE: We ignore potential failures here during a system scan (like
2896                // the rest of the commands above) because there's precious little we
2897                // can do about it. A settings error is reported, though.
2898                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2899            }
2900
2901            // Now that we know all the packages we are keeping,
2902            // read and update their last usage times.
2903            mPackageUsage.read(mPackages);
2904            mCompilerStats.read();
2905
2906            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2907                    SystemClock.uptimeMillis());
2908            Slog.i(TAG, "Time to scan packages: "
2909                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2910                    + " seconds");
2911
2912            // If the platform SDK has changed since the last time we booted,
2913            // we need to re-grant app permission to catch any new ones that
2914            // appear.  This is really a hack, and means that apps can in some
2915            // cases get permissions that the user didn't initially explicitly
2916            // allow...  it would be nice to have some better way to handle
2917            // this situation.
2918            int updateFlags = UPDATE_PERMISSIONS_ALL;
2919            if (ver.sdkVersion != mSdkVersion) {
2920                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2921                        + mSdkVersion + "; regranting permissions for internal storage");
2922                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2923            }
2924            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2925            ver.sdkVersion = mSdkVersion;
2926
2927            // If this is the first boot or an update from pre-M, and it is a normal
2928            // boot, then we need to initialize the default preferred apps across
2929            // all defined users.
2930            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2931                for (UserInfo user : sUserManager.getUsers(true)) {
2932                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2933                    applyFactoryDefaultBrowserLPw(user.id);
2934                    primeDomainVerificationsLPw(user.id);
2935                }
2936            }
2937
2938            // Prepare storage for system user really early during boot,
2939            // since core system apps like SettingsProvider and SystemUI
2940            // can't wait for user to start
2941            final int storageFlags;
2942            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2943                storageFlags = StorageManager.FLAG_STORAGE_DE;
2944            } else {
2945                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2946            }
2947            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2948                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2949                    true /* onlyCoreApps */);
2950            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2951                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2952                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2953                traceLog.traceBegin("AppDataFixup");
2954                try {
2955                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2956                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2957                } catch (InstallerException e) {
2958                    Slog.w(TAG, "Trouble fixing GIDs", e);
2959                }
2960                traceLog.traceEnd();
2961
2962                traceLog.traceBegin("AppDataPrepare");
2963                if (deferPackages == null || deferPackages.isEmpty()) {
2964                    return;
2965                }
2966                int count = 0;
2967                for (String pkgName : deferPackages) {
2968                    PackageParser.Package pkg = null;
2969                    synchronized (mPackages) {
2970                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2971                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2972                            pkg = ps.pkg;
2973                        }
2974                    }
2975                    if (pkg != null) {
2976                        synchronized (mInstallLock) {
2977                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2978                                    true /* maybeMigrateAppData */);
2979                        }
2980                        count++;
2981                    }
2982                }
2983                traceLog.traceEnd();
2984                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2985            }, "prepareAppData");
2986
2987            // If this is first boot after an OTA, and a normal boot, then
2988            // we need to clear code cache directories.
2989            // Note that we do *not* clear the application profiles. These remain valid
2990            // across OTAs and are used to drive profile verification (post OTA) and
2991            // profile compilation (without waiting to collect a fresh set of profiles).
2992            if (mIsUpgrade && !onlyCore) {
2993                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2994                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2995                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2996                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2997                        // No apps are running this early, so no need to freeze
2998                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2999                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3000                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3001                    }
3002                }
3003                ver.fingerprint = Build.FINGERPRINT;
3004            }
3005
3006            checkDefaultBrowser();
3007
3008            // clear only after permissions and other defaults have been updated
3009            mExistingSystemPackages.clear();
3010            mPromoteSystemApps = false;
3011
3012            // All the changes are done during package scanning.
3013            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3014
3015            // can downgrade to reader
3016            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3017            mSettings.writeLPr();
3018            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3019            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3020                    SystemClock.uptimeMillis());
3021
3022            if (!mOnlyCore) {
3023                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3024                mRequiredInstallerPackage = getRequiredInstallerLPr();
3025                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3026                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3027                if (mIntentFilterVerifierComponent != null) {
3028                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3029                            mIntentFilterVerifierComponent);
3030                } else {
3031                    mIntentFilterVerifier = null;
3032                }
3033                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3034                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3035                        SharedLibraryInfo.VERSION_UNDEFINED);
3036                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3037                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3038                        SharedLibraryInfo.VERSION_UNDEFINED);
3039            } else {
3040                mRequiredVerifierPackage = null;
3041                mRequiredInstallerPackage = null;
3042                mRequiredUninstallerPackage = null;
3043                mIntentFilterVerifierComponent = null;
3044                mIntentFilterVerifier = null;
3045                mServicesSystemSharedLibraryPackageName = null;
3046                mSharedSystemSharedLibraryPackageName = null;
3047            }
3048
3049            mInstallerService = new PackageInstallerService(context, this);
3050            final Pair<ComponentName, String> instantAppResolverComponent =
3051                    getInstantAppResolverLPr();
3052            if (instantAppResolverComponent != null) {
3053                if (DEBUG_EPHEMERAL) {
3054                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3055                }
3056                mInstantAppResolverConnection = new EphemeralResolverConnection(
3057                        mContext, instantAppResolverComponent.first,
3058                        instantAppResolverComponent.second);
3059                mInstantAppResolverSettingsComponent =
3060                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3061            } else {
3062                mInstantAppResolverConnection = null;
3063                mInstantAppResolverSettingsComponent = null;
3064            }
3065            updateInstantAppInstallerLocked(null);
3066
3067            // Read and update the usage of dex files.
3068            // Do this at the end of PM init so that all the packages have their
3069            // data directory reconciled.
3070            // At this point we know the code paths of the packages, so we can validate
3071            // the disk file and build the internal cache.
3072            // The usage file is expected to be small so loading and verifying it
3073            // should take a fairly small time compare to the other activities (e.g. package
3074            // scanning).
3075            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3076            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3077            for (int userId : currentUserIds) {
3078                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3079            }
3080            mDexManager.load(userPackages);
3081            if (mIsUpgrade) {
3082                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3083                        (int) (SystemClock.uptimeMillis() - startTime));
3084            }
3085        } // synchronized (mPackages)
3086        } // synchronized (mInstallLock)
3087
3088        // Now after opening every single application zip, make sure they
3089        // are all flushed.  Not really needed, but keeps things nice and
3090        // tidy.
3091        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3092        Runtime.getRuntime().gc();
3093        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3094
3095        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3096        FallbackCategoryProvider.loadFallbacks();
3097        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3098
3099        // The initial scanning above does many calls into installd while
3100        // holding the mPackages lock, but we're mostly interested in yelling
3101        // once we have a booted system.
3102        mInstaller.setWarnIfHeld(mPackages);
3103
3104        // Expose private service for system components to use.
3105        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3106        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3107    }
3108
3109    /**
3110     * Uncompress and install stub applications.
3111     * <p>In order to save space on the system partition, some applications are shipped in a
3112     * compressed form. In addition the compressed bits for the full application, the
3113     * system image contains a tiny stub comprised of only the Android manifest.
3114     * <p>During the first boot, attempt to uncompress and install the full application. If
3115     * the application can't be installed for any reason, disable the stub and prevent
3116     * uncompressing the full application during future boots.
3117     * <p>In order to forcefully attempt an installation of a full application, go to app
3118     * settings and enable the application.
3119     */
3120    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3121        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3122            final String pkgName = stubSystemApps.get(i);
3123            // skip if the system package is already disabled
3124            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3125                stubSystemApps.remove(i);
3126                continue;
3127            }
3128            // skip if the package isn't installed (?!); this should never happen
3129            final PackageParser.Package pkg = mPackages.get(pkgName);
3130            if (pkg == null) {
3131                stubSystemApps.remove(i);
3132                continue;
3133            }
3134            // skip if the package has been disabled by the user
3135            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3136            if (ps != null) {
3137                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3138                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3139                    stubSystemApps.remove(i);
3140                    continue;
3141                }
3142            }
3143
3144            if (DEBUG_COMPRESSION) {
3145                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3146            }
3147
3148            // uncompress the binary to its eventual destination on /data
3149            final File scanFile = decompressPackage(pkg);
3150            if (scanFile == null) {
3151                continue;
3152            }
3153
3154            // install the package to replace the stub on /system
3155            try {
3156                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3157                removePackageLI(pkg, true /*chatty*/);
3158                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3159                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3160                        UserHandle.USER_SYSTEM, "android");
3161                stubSystemApps.remove(i);
3162                continue;
3163            } catch (PackageManagerException e) {
3164                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3165            }
3166
3167            // any failed attempt to install the package will be cleaned up later
3168        }
3169
3170        // disable any stub still left; these failed to install the full application
3171        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3172            final String pkgName = stubSystemApps.get(i);
3173            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3174            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3175                    UserHandle.USER_SYSTEM, "android");
3176            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3177        }
3178    }
3179
3180    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3181        if (DEBUG_COMPRESSION) {
3182            Slog.i(TAG, "Decompress file"
3183                    + "; src: " + srcFile.getAbsolutePath()
3184                    + ", dst: " + dstFile.getAbsolutePath());
3185        }
3186        try (
3187                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3188                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3189        ) {
3190            Streams.copy(fileIn, fileOut);
3191            Os.chmod(dstFile.getAbsolutePath(), 0644);
3192            return PackageManager.INSTALL_SUCCEEDED;
3193        } catch (IOException e) {
3194            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3195                    + "; src: " + srcFile.getAbsolutePath()
3196                    + ", dst: " + dstFile.getAbsolutePath());
3197        }
3198        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3199    }
3200
3201    private File[] getCompressedFiles(String codePath) {
3202        final File stubCodePath = new File(codePath);
3203        final String stubName = stubCodePath.getName();
3204
3205        // The layout of a compressed package on a given partition is as follows :
3206        //
3207        // Compressed artifacts:
3208        //
3209        // /partition/ModuleName/foo.gz
3210        // /partation/ModuleName/bar.gz
3211        //
3212        // Stub artifact:
3213        //
3214        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3215        //
3216        // In other words, stub is on the same partition as the compressed artifacts
3217        // and in a directory that's suffixed with "-Stub".
3218        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3219        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3220            return null;
3221        }
3222
3223        final File stubParentDir = stubCodePath.getParentFile();
3224        if (stubParentDir == null) {
3225            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3226            return null;
3227        }
3228
3229        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3230        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3231            @Override
3232            public boolean accept(File dir, String name) {
3233                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3234            }
3235        });
3236
3237        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3238            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3239        }
3240
3241        return files;
3242    }
3243
3244    private boolean compressedFileExists(String codePath) {
3245        final File[] compressedFiles = getCompressedFiles(codePath);
3246        return compressedFiles != null && compressedFiles.length > 0;
3247    }
3248
3249    /**
3250     * Decompresses the given package on the system image onto
3251     * the /data partition.
3252     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3253     */
3254    private File decompressPackage(PackageParser.Package pkg) {
3255        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3256        if (compressedFiles == null || compressedFiles.length == 0) {
3257            if (DEBUG_COMPRESSION) {
3258                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3259            }
3260            return null;
3261        }
3262        final File dstCodePath =
3263                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3264        int ret = PackageManager.INSTALL_SUCCEEDED;
3265        try {
3266            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3267            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3268            for (File srcFile : compressedFiles) {
3269                final String srcFileName = srcFile.getName();
3270                final String dstFileName = srcFileName.substring(
3271                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3272                final File dstFile = new File(dstCodePath, dstFileName);
3273                ret = decompressFile(srcFile, dstFile);
3274                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3275                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3276                            + "; pkg: " + pkg.packageName
3277                            + ", file: " + dstFileName);
3278                    break;
3279                }
3280            }
3281        } catch (ErrnoException e) {
3282            logCriticalInfo(Log.ERROR, "Failed to decompress"
3283                    + "; pkg: " + pkg.packageName
3284                    + ", err: " + e.errno);
3285        }
3286        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3287            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3288            NativeLibraryHelper.Handle handle = null;
3289            try {
3290                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3291                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3292                        null /*abiOverride*/);
3293            } catch (IOException e) {
3294                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3295                        + "; pkg: " + pkg.packageName);
3296                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3297            } finally {
3298                IoUtils.closeQuietly(handle);
3299            }
3300        }
3301        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3302            if (dstCodePath == null || !dstCodePath.exists()) {
3303                return null;
3304            }
3305            removeCodePathLI(dstCodePath);
3306            return null;
3307        }
3308        return dstCodePath;
3309    }
3310
3311    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3312        // we're only interested in updating the installer appliction when 1) it's not
3313        // already set or 2) the modified package is the installer
3314        if (mInstantAppInstallerActivity != null
3315                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3316                        .equals(modifiedPackage)) {
3317            return;
3318        }
3319        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3320    }
3321
3322    private static File preparePackageParserCache(boolean isUpgrade) {
3323        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3324            return null;
3325        }
3326
3327        // Disable package parsing on eng builds to allow for faster incremental development.
3328        if (Build.IS_ENG) {
3329            return null;
3330        }
3331
3332        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3333            Slog.i(TAG, "Disabling package parser cache due to system property.");
3334            return null;
3335        }
3336
3337        // The base directory for the package parser cache lives under /data/system/.
3338        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3339                "package_cache");
3340        if (cacheBaseDir == null) {
3341            return null;
3342        }
3343
3344        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3345        // This also serves to "GC" unused entries when the package cache version changes (which
3346        // can only happen during upgrades).
3347        if (isUpgrade) {
3348            FileUtils.deleteContents(cacheBaseDir);
3349        }
3350
3351
3352        // Return the versioned package cache directory. This is something like
3353        // "/data/system/package_cache/1"
3354        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3355
3356        // The following is a workaround to aid development on non-numbered userdebug
3357        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3358        // the system partition is newer.
3359        //
3360        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3361        // that starts with "eng." to signify that this is an engineering build and not
3362        // destined for release.
3363        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3364            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3365
3366            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3367            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3368            // in general and should not be used for production changes. In this specific case,
3369            // we know that they will work.
3370            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3371            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3372                FileUtils.deleteContents(cacheBaseDir);
3373                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3374            }
3375        }
3376
3377        return cacheDir;
3378    }
3379
3380    @Override
3381    public boolean isFirstBoot() {
3382        // allow instant applications
3383        return mFirstBoot;
3384    }
3385
3386    @Override
3387    public boolean isOnlyCoreApps() {
3388        // allow instant applications
3389        return mOnlyCore;
3390    }
3391
3392    @Override
3393    public boolean isUpgrade() {
3394        // allow instant applications
3395        return mIsUpgrade;
3396    }
3397
3398    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3399        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3400
3401        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3402                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3403                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3404        if (matches.size() == 1) {
3405            return matches.get(0).getComponentInfo().packageName;
3406        } else if (matches.size() == 0) {
3407            Log.e(TAG, "There should probably be a verifier, but, none were found");
3408            return null;
3409        }
3410        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3411    }
3412
3413    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3414        synchronized (mPackages) {
3415            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3416            if (libraryEntry == null) {
3417                throw new IllegalStateException("Missing required shared library:" + name);
3418            }
3419            return libraryEntry.apk;
3420        }
3421    }
3422
3423    private @NonNull String getRequiredInstallerLPr() {
3424        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3425        intent.addCategory(Intent.CATEGORY_DEFAULT);
3426        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3427
3428        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3429                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3430                UserHandle.USER_SYSTEM);
3431        if (matches.size() == 1) {
3432            ResolveInfo resolveInfo = matches.get(0);
3433            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3434                throw new RuntimeException("The installer must be a privileged app");
3435            }
3436            return matches.get(0).getComponentInfo().packageName;
3437        } else {
3438            throw new RuntimeException("There must be exactly one installer; found " + matches);
3439        }
3440    }
3441
3442    private @NonNull String getRequiredUninstallerLPr() {
3443        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3444        intent.addCategory(Intent.CATEGORY_DEFAULT);
3445        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3446
3447        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3448                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3449                UserHandle.USER_SYSTEM);
3450        if (resolveInfo == null ||
3451                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3452            throw new RuntimeException("There must be exactly one uninstaller; found "
3453                    + resolveInfo);
3454        }
3455        return resolveInfo.getComponentInfo().packageName;
3456    }
3457
3458    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3459        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3460
3461        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3462                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3463                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3464        ResolveInfo best = null;
3465        final int N = matches.size();
3466        for (int i = 0; i < N; i++) {
3467            final ResolveInfo cur = matches.get(i);
3468            final String packageName = cur.getComponentInfo().packageName;
3469            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3470                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3471                continue;
3472            }
3473
3474            if (best == null || cur.priority > best.priority) {
3475                best = cur;
3476            }
3477        }
3478
3479        if (best != null) {
3480            return best.getComponentInfo().getComponentName();
3481        }
3482        Slog.w(TAG, "Intent filter verifier not found");
3483        return null;
3484    }
3485
3486    @Override
3487    public @Nullable ComponentName getInstantAppResolverComponent() {
3488        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3489            return null;
3490        }
3491        synchronized (mPackages) {
3492            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3493            if (instantAppResolver == null) {
3494                return null;
3495            }
3496            return instantAppResolver.first;
3497        }
3498    }
3499
3500    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3501        final String[] packageArray =
3502                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3503        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3504            if (DEBUG_EPHEMERAL) {
3505                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3506            }
3507            return null;
3508        }
3509
3510        final int callingUid = Binder.getCallingUid();
3511        final int resolveFlags =
3512                MATCH_DIRECT_BOOT_AWARE
3513                | MATCH_DIRECT_BOOT_UNAWARE
3514                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3515        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3516        final Intent resolverIntent = new Intent(actionName);
3517        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3518                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3519        // temporarily look for the old action
3520        if (resolvers.size() == 0) {
3521            if (DEBUG_EPHEMERAL) {
3522                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3523            }
3524            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3525            resolverIntent.setAction(actionName);
3526            resolvers = queryIntentServicesInternal(resolverIntent, null,
3527                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3528        }
3529        final int N = resolvers.size();
3530        if (N == 0) {
3531            if (DEBUG_EPHEMERAL) {
3532                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3533            }
3534            return null;
3535        }
3536
3537        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3538        for (int i = 0; i < N; i++) {
3539            final ResolveInfo info = resolvers.get(i);
3540
3541            if (info.serviceInfo == null) {
3542                continue;
3543            }
3544
3545            final String packageName = info.serviceInfo.packageName;
3546            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3547                if (DEBUG_EPHEMERAL) {
3548                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3549                            + " pkg: " + packageName + ", info:" + info);
3550                }
3551                continue;
3552            }
3553
3554            if (DEBUG_EPHEMERAL) {
3555                Slog.v(TAG, "Ephemeral resolver found;"
3556                        + " pkg: " + packageName + ", info:" + info);
3557            }
3558            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3559        }
3560        if (DEBUG_EPHEMERAL) {
3561            Slog.v(TAG, "Ephemeral resolver NOT found");
3562        }
3563        return null;
3564    }
3565
3566    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3567        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3568        intent.addCategory(Intent.CATEGORY_DEFAULT);
3569        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3570
3571        final int resolveFlags =
3572                MATCH_DIRECT_BOOT_AWARE
3573                | MATCH_DIRECT_BOOT_UNAWARE
3574                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3575        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3576                resolveFlags, UserHandle.USER_SYSTEM);
3577        // temporarily look for the old action
3578        if (matches.isEmpty()) {
3579            if (DEBUG_EPHEMERAL) {
3580                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3581            }
3582            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3583            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3584                    resolveFlags, UserHandle.USER_SYSTEM);
3585        }
3586        Iterator<ResolveInfo> iter = matches.iterator();
3587        while (iter.hasNext()) {
3588            final ResolveInfo rInfo = iter.next();
3589            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3590            if (ps != null) {
3591                final PermissionsState permissionsState = ps.getPermissionsState();
3592                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3593                    continue;
3594                }
3595            }
3596            iter.remove();
3597        }
3598        if (matches.size() == 0) {
3599            return null;
3600        } else if (matches.size() == 1) {
3601            return (ActivityInfo) matches.get(0).getComponentInfo();
3602        } else {
3603            throw new RuntimeException(
3604                    "There must be at most one ephemeral installer; found " + matches);
3605        }
3606    }
3607
3608    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3609            @NonNull ComponentName resolver) {
3610        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3611                .addCategory(Intent.CATEGORY_DEFAULT)
3612                .setPackage(resolver.getPackageName());
3613        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3614        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3615                UserHandle.USER_SYSTEM);
3616        // temporarily look for the old action
3617        if (matches.isEmpty()) {
3618            if (DEBUG_EPHEMERAL) {
3619                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3620            }
3621            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3622            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3623                    UserHandle.USER_SYSTEM);
3624        }
3625        if (matches.isEmpty()) {
3626            return null;
3627        }
3628        return matches.get(0).getComponentInfo().getComponentName();
3629    }
3630
3631    private void primeDomainVerificationsLPw(int userId) {
3632        if (DEBUG_DOMAIN_VERIFICATION) {
3633            Slog.d(TAG, "Priming domain verifications in user " + userId);
3634        }
3635
3636        SystemConfig systemConfig = SystemConfig.getInstance();
3637        ArraySet<String> packages = systemConfig.getLinkedApps();
3638
3639        for (String packageName : packages) {
3640            PackageParser.Package pkg = mPackages.get(packageName);
3641            if (pkg != null) {
3642                if (!pkg.isSystemApp()) {
3643                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3644                    continue;
3645                }
3646
3647                ArraySet<String> domains = null;
3648                for (PackageParser.Activity a : pkg.activities) {
3649                    for (ActivityIntentInfo filter : a.intents) {
3650                        if (hasValidDomains(filter)) {
3651                            if (domains == null) {
3652                                domains = new ArraySet<String>();
3653                            }
3654                            domains.addAll(filter.getHostsList());
3655                        }
3656                    }
3657                }
3658
3659                if (domains != null && domains.size() > 0) {
3660                    if (DEBUG_DOMAIN_VERIFICATION) {
3661                        Slog.v(TAG, "      + " + packageName);
3662                    }
3663                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3664                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3665                    // and then 'always' in the per-user state actually used for intent resolution.
3666                    final IntentFilterVerificationInfo ivi;
3667                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3668                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3669                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3670                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3671                } else {
3672                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3673                            + "' does not handle web links");
3674                }
3675            } else {
3676                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3677            }
3678        }
3679
3680        scheduleWritePackageRestrictionsLocked(userId);
3681        scheduleWriteSettingsLocked();
3682    }
3683
3684    private void applyFactoryDefaultBrowserLPw(int userId) {
3685        // The default browser app's package name is stored in a string resource,
3686        // with a product-specific overlay used for vendor customization.
3687        String browserPkg = mContext.getResources().getString(
3688                com.android.internal.R.string.default_browser);
3689        if (!TextUtils.isEmpty(browserPkg)) {
3690            // non-empty string => required to be a known package
3691            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3692            if (ps == null) {
3693                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3694                browserPkg = null;
3695            } else {
3696                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3697            }
3698        }
3699
3700        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3701        // default.  If there's more than one, just leave everything alone.
3702        if (browserPkg == null) {
3703            calculateDefaultBrowserLPw(userId);
3704        }
3705    }
3706
3707    private void calculateDefaultBrowserLPw(int userId) {
3708        List<String> allBrowsers = resolveAllBrowserApps(userId);
3709        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3710        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3711    }
3712
3713    private List<String> resolveAllBrowserApps(int userId) {
3714        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3715        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3716                PackageManager.MATCH_ALL, userId);
3717
3718        final int count = list.size();
3719        List<String> result = new ArrayList<String>(count);
3720        for (int i=0; i<count; i++) {
3721            ResolveInfo info = list.get(i);
3722            if (info.activityInfo == null
3723                    || !info.handleAllWebDataURI
3724                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3725                    || result.contains(info.activityInfo.packageName)) {
3726                continue;
3727            }
3728            result.add(info.activityInfo.packageName);
3729        }
3730
3731        return result;
3732    }
3733
3734    private boolean packageIsBrowser(String packageName, int userId) {
3735        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3736                PackageManager.MATCH_ALL, userId);
3737        final int N = list.size();
3738        for (int i = 0; i < N; i++) {
3739            ResolveInfo info = list.get(i);
3740            if (packageName.equals(info.activityInfo.packageName)) {
3741                return true;
3742            }
3743        }
3744        return false;
3745    }
3746
3747    private void checkDefaultBrowser() {
3748        final int myUserId = UserHandle.myUserId();
3749        final String packageName = getDefaultBrowserPackageName(myUserId);
3750        if (packageName != null) {
3751            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3752            if (info == null) {
3753                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3754                synchronized (mPackages) {
3755                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3756                }
3757            }
3758        }
3759    }
3760
3761    @Override
3762    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3763            throws RemoteException {
3764        try {
3765            return super.onTransact(code, data, reply, flags);
3766        } catch (RuntimeException e) {
3767            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3768                Slog.wtf(TAG, "Package Manager Crash", e);
3769            }
3770            throw e;
3771        }
3772    }
3773
3774    static int[] appendInts(int[] cur, int[] add) {
3775        if (add == null) return cur;
3776        if (cur == null) return add;
3777        final int N = add.length;
3778        for (int i=0; i<N; i++) {
3779            cur = appendInt(cur, add[i]);
3780        }
3781        return cur;
3782    }
3783
3784    /**
3785     * Returns whether or not a full application can see an instant application.
3786     * <p>
3787     * Currently, there are three cases in which this can occur:
3788     * <ol>
3789     * <li>The calling application is a "special" process. The special
3790     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3791     *     and {@code 0}</li>
3792     * <li>The calling application has the permission
3793     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3794     * <li>The calling application is the default launcher on the
3795     *     system partition.</li>
3796     * </ol>
3797     */
3798    private boolean canViewInstantApps(int callingUid, int userId) {
3799        if (callingUid == Process.SYSTEM_UID
3800                || callingUid == Process.SHELL_UID
3801                || callingUid == Process.ROOT_UID) {
3802            return true;
3803        }
3804        if (mContext.checkCallingOrSelfPermission(
3805                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3806            return true;
3807        }
3808        if (mContext.checkCallingOrSelfPermission(
3809                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3810            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3811            if (homeComponent != null
3812                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3813                return true;
3814            }
3815        }
3816        return false;
3817    }
3818
3819    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3820        if (!sUserManager.exists(userId)) return null;
3821        if (ps == null) {
3822            return null;
3823        }
3824        PackageParser.Package p = ps.pkg;
3825        if (p == null) {
3826            return null;
3827        }
3828        final int callingUid = Binder.getCallingUid();
3829        // Filter out ephemeral app metadata:
3830        //   * The system/shell/root can see metadata for any app
3831        //   * An installed app can see metadata for 1) other installed apps
3832        //     and 2) ephemeral apps that have explicitly interacted with it
3833        //   * Ephemeral apps can only see their own data and exposed installed apps
3834        //   * Holding a signature permission allows seeing instant apps
3835        if (filterAppAccessLPr(ps, callingUid, userId)) {
3836            return null;
3837        }
3838
3839        final PermissionsState permissionsState = ps.getPermissionsState();
3840
3841        // Compute GIDs only if requested
3842        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3843                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3844        // Compute granted permissions only if package has requested permissions
3845        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3846                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3847        final PackageUserState state = ps.readUserState(userId);
3848
3849        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3850                && ps.isSystem()) {
3851            flags |= MATCH_ANY_USER;
3852        }
3853
3854        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3855                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3856
3857        if (packageInfo == null) {
3858            return null;
3859        }
3860
3861        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3862                resolveExternalPackageNameLPr(p);
3863
3864        return packageInfo;
3865    }
3866
3867    @Override
3868    public void checkPackageStartable(String packageName, int userId) {
3869        final int callingUid = Binder.getCallingUid();
3870        if (getInstantAppPackageName(callingUid) != null) {
3871            throw new SecurityException("Instant applications don't have access to this method");
3872        }
3873        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3874        synchronized (mPackages) {
3875            final PackageSetting ps = mSettings.mPackages.get(packageName);
3876            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3877                throw new SecurityException("Package " + packageName + " was not found!");
3878            }
3879
3880            if (!ps.getInstalled(userId)) {
3881                throw new SecurityException(
3882                        "Package " + packageName + " was not installed for user " + userId + "!");
3883            }
3884
3885            if (mSafeMode && !ps.isSystem()) {
3886                throw new SecurityException("Package " + packageName + " not a system app!");
3887            }
3888
3889            if (mFrozenPackages.contains(packageName)) {
3890                throw new SecurityException("Package " + packageName + " is currently frozen!");
3891            }
3892
3893            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3894                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3895            }
3896        }
3897    }
3898
3899    @Override
3900    public boolean isPackageAvailable(String packageName, int userId) {
3901        if (!sUserManager.exists(userId)) return false;
3902        final int callingUid = Binder.getCallingUid();
3903        enforceCrossUserPermission(callingUid, userId,
3904                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3905        synchronized (mPackages) {
3906            PackageParser.Package p = mPackages.get(packageName);
3907            if (p != null) {
3908                final PackageSetting ps = (PackageSetting) p.mExtras;
3909                if (filterAppAccessLPr(ps, callingUid, userId)) {
3910                    return false;
3911                }
3912                if (ps != null) {
3913                    final PackageUserState state = ps.readUserState(userId);
3914                    if (state != null) {
3915                        return PackageParser.isAvailable(state);
3916                    }
3917                }
3918            }
3919        }
3920        return false;
3921    }
3922
3923    @Override
3924    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3925        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3926                flags, Binder.getCallingUid(), userId);
3927    }
3928
3929    @Override
3930    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3931            int flags, int userId) {
3932        return getPackageInfoInternal(versionedPackage.getPackageName(),
3933                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3934    }
3935
3936    /**
3937     * Important: The provided filterCallingUid is used exclusively to filter out packages
3938     * that can be seen based on user state. It's typically the original caller uid prior
3939     * to clearing. Because it can only be provided by trusted code, it's value can be
3940     * trusted and will be used as-is; unlike userId which will be validated by this method.
3941     */
3942    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3943            int flags, int filterCallingUid, int userId) {
3944        if (!sUserManager.exists(userId)) return null;
3945        flags = updateFlagsForPackage(flags, userId, packageName);
3946        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3947                false /* requireFullPermission */, false /* checkShell */, "get package info");
3948
3949        // reader
3950        synchronized (mPackages) {
3951            // Normalize package name to handle renamed packages and static libs
3952            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3953
3954            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3955            if (matchFactoryOnly) {
3956                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3957                if (ps != null) {
3958                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3959                        return null;
3960                    }
3961                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3962                        return null;
3963                    }
3964                    return generatePackageInfo(ps, flags, userId);
3965                }
3966            }
3967
3968            PackageParser.Package p = mPackages.get(packageName);
3969            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3970                return null;
3971            }
3972            if (DEBUG_PACKAGE_INFO)
3973                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3974            if (p != null) {
3975                final PackageSetting ps = (PackageSetting) p.mExtras;
3976                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3977                    return null;
3978                }
3979                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3980                    return null;
3981                }
3982                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3983            }
3984            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3985                final PackageSetting ps = mSettings.mPackages.get(packageName);
3986                if (ps == null) return null;
3987                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3988                    return null;
3989                }
3990                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3991                    return null;
3992                }
3993                return generatePackageInfo(ps, flags, userId);
3994            }
3995        }
3996        return null;
3997    }
3998
3999    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4000        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4001            return true;
4002        }
4003        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4004            return true;
4005        }
4006        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4007            return true;
4008        }
4009        return false;
4010    }
4011
4012    private boolean isComponentVisibleToInstantApp(
4013            @Nullable ComponentName component, @ComponentType int type) {
4014        if (type == TYPE_ACTIVITY) {
4015            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4016            return activity != null
4017                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4018                    : false;
4019        } else if (type == TYPE_RECEIVER) {
4020            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4021            return activity != null
4022                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4023                    : false;
4024        } else if (type == TYPE_SERVICE) {
4025            final PackageParser.Service service = mServices.mServices.get(component);
4026            return service != null
4027                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4028                    : false;
4029        } else if (type == TYPE_PROVIDER) {
4030            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4031            return provider != null
4032                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4033                    : false;
4034        } else if (type == TYPE_UNKNOWN) {
4035            return isComponentVisibleToInstantApp(component);
4036        }
4037        return false;
4038    }
4039
4040    /**
4041     * Returns whether or not access to the application should be filtered.
4042     * <p>
4043     * Access may be limited based upon whether the calling or target applications
4044     * are instant applications.
4045     *
4046     * @see #canAccessInstantApps(int)
4047     */
4048    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4049            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4050        // if we're in an isolated process, get the real calling UID
4051        if (Process.isIsolated(callingUid)) {
4052            callingUid = mIsolatedOwners.get(callingUid);
4053        }
4054        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4055        final boolean callerIsInstantApp = instantAppPkgName != null;
4056        if (ps == null) {
4057            if (callerIsInstantApp) {
4058                // pretend the application exists, but, needs to be filtered
4059                return true;
4060            }
4061            return false;
4062        }
4063        // if the target and caller are the same application, don't filter
4064        if (isCallerSameApp(ps.name, callingUid)) {
4065            return false;
4066        }
4067        if (callerIsInstantApp) {
4068            // request for a specific component; if it hasn't been explicitly exposed, filter
4069            if (component != null) {
4070                return !isComponentVisibleToInstantApp(component, componentType);
4071            }
4072            // request for application; if no components have been explicitly exposed, filter
4073            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4074        }
4075        if (ps.getInstantApp(userId)) {
4076            // caller can see all components of all instant applications, don't filter
4077            if (canViewInstantApps(callingUid, userId)) {
4078                return false;
4079            }
4080            // request for a specific instant application component, filter
4081            if (component != null) {
4082                return true;
4083            }
4084            // request for an instant application; if the caller hasn't been granted access, filter
4085            return !mInstantAppRegistry.isInstantAccessGranted(
4086                    userId, UserHandle.getAppId(callingUid), ps.appId);
4087        }
4088        return false;
4089    }
4090
4091    /**
4092     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4093     */
4094    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4095        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4096    }
4097
4098    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4099            int flags) {
4100        // Callers can access only the libs they depend on, otherwise they need to explicitly
4101        // ask for the shared libraries given the caller is allowed to access all static libs.
4102        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4103            // System/shell/root get to see all static libs
4104            final int appId = UserHandle.getAppId(uid);
4105            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4106                    || appId == Process.ROOT_UID) {
4107                return false;
4108            }
4109        }
4110
4111        // No package means no static lib as it is always on internal storage
4112        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4113            return false;
4114        }
4115
4116        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4117                ps.pkg.staticSharedLibVersion);
4118        if (libEntry == null) {
4119            return false;
4120        }
4121
4122        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4123        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4124        if (uidPackageNames == null) {
4125            return true;
4126        }
4127
4128        for (String uidPackageName : uidPackageNames) {
4129            if (ps.name.equals(uidPackageName)) {
4130                return false;
4131            }
4132            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4133            if (uidPs != null) {
4134                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4135                        libEntry.info.getName());
4136                if (index < 0) {
4137                    continue;
4138                }
4139                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4140                    return false;
4141                }
4142            }
4143        }
4144        return true;
4145    }
4146
4147    @Override
4148    public String[] currentToCanonicalPackageNames(String[] names) {
4149        final int callingUid = Binder.getCallingUid();
4150        if (getInstantAppPackageName(callingUid) != null) {
4151            return names;
4152        }
4153        final String[] out = new String[names.length];
4154        // reader
4155        synchronized (mPackages) {
4156            final int callingUserId = UserHandle.getUserId(callingUid);
4157            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4158            for (int i=names.length-1; i>=0; i--) {
4159                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4160                boolean translateName = false;
4161                if (ps != null && ps.realName != null) {
4162                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4163                    translateName = !targetIsInstantApp
4164                            || canViewInstantApps
4165                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4166                                    UserHandle.getAppId(callingUid), ps.appId);
4167                }
4168                out[i] = translateName ? ps.realName : names[i];
4169            }
4170        }
4171        return out;
4172    }
4173
4174    @Override
4175    public String[] canonicalToCurrentPackageNames(String[] names) {
4176        final int callingUid = Binder.getCallingUid();
4177        if (getInstantAppPackageName(callingUid) != null) {
4178            return names;
4179        }
4180        final String[] out = new String[names.length];
4181        // reader
4182        synchronized (mPackages) {
4183            final int callingUserId = UserHandle.getUserId(callingUid);
4184            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4185            for (int i=names.length-1; i>=0; i--) {
4186                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4187                boolean translateName = false;
4188                if (cur != null) {
4189                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4190                    final boolean targetIsInstantApp =
4191                            ps != null && ps.getInstantApp(callingUserId);
4192                    translateName = !targetIsInstantApp
4193                            || canViewInstantApps
4194                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4195                                    UserHandle.getAppId(callingUid), ps.appId);
4196                }
4197                out[i] = translateName ? cur : names[i];
4198            }
4199        }
4200        return out;
4201    }
4202
4203    @Override
4204    public int getPackageUid(String packageName, int flags, int userId) {
4205        if (!sUserManager.exists(userId)) return -1;
4206        final int callingUid = Binder.getCallingUid();
4207        flags = updateFlagsForPackage(flags, userId, packageName);
4208        enforceCrossUserPermission(callingUid, userId,
4209                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4210
4211        // reader
4212        synchronized (mPackages) {
4213            final PackageParser.Package p = mPackages.get(packageName);
4214            if (p != null && p.isMatch(flags)) {
4215                PackageSetting ps = (PackageSetting) p.mExtras;
4216                if (filterAppAccessLPr(ps, callingUid, userId)) {
4217                    return -1;
4218                }
4219                return UserHandle.getUid(userId, p.applicationInfo.uid);
4220            }
4221            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4222                final PackageSetting ps = mSettings.mPackages.get(packageName);
4223                if (ps != null && ps.isMatch(flags)
4224                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4225                    return UserHandle.getUid(userId, ps.appId);
4226                }
4227            }
4228        }
4229
4230        return -1;
4231    }
4232
4233    @Override
4234    public int[] getPackageGids(String packageName, int flags, int userId) {
4235        if (!sUserManager.exists(userId)) return null;
4236        final int callingUid = Binder.getCallingUid();
4237        flags = updateFlagsForPackage(flags, userId, packageName);
4238        enforceCrossUserPermission(callingUid, userId,
4239                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4240
4241        // reader
4242        synchronized (mPackages) {
4243            final PackageParser.Package p = mPackages.get(packageName);
4244            if (p != null && p.isMatch(flags)) {
4245                PackageSetting ps = (PackageSetting) p.mExtras;
4246                if (filterAppAccessLPr(ps, callingUid, userId)) {
4247                    return null;
4248                }
4249                // TODO: Shouldn't this be checking for package installed state for userId and
4250                // return null?
4251                return ps.getPermissionsState().computeGids(userId);
4252            }
4253            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4254                final PackageSetting ps = mSettings.mPackages.get(packageName);
4255                if (ps != null && ps.isMatch(flags)
4256                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4257                    return ps.getPermissionsState().computeGids(userId);
4258                }
4259            }
4260        }
4261
4262        return null;
4263    }
4264
4265    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4266        if (bp.perm != null) {
4267            return PackageParser.generatePermissionInfo(bp.perm, flags);
4268        }
4269        PermissionInfo pi = new PermissionInfo();
4270        pi.name = bp.name;
4271        pi.packageName = bp.sourcePackage;
4272        pi.nonLocalizedLabel = bp.name;
4273        pi.protectionLevel = bp.protectionLevel;
4274        return pi;
4275    }
4276
4277    @Override
4278    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4279        final int callingUid = Binder.getCallingUid();
4280        if (getInstantAppPackageName(callingUid) != null) {
4281            return null;
4282        }
4283        // reader
4284        synchronized (mPackages) {
4285            final BasePermission p = mSettings.mPermissions.get(name);
4286            if (p == null) {
4287                return null;
4288            }
4289            // If the caller is an app that targets pre 26 SDK drop protection flags.
4290            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4291            if (permissionInfo != null) {
4292                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4293                        permissionInfo.protectionLevel, packageName, callingUid);
4294                if (permissionInfo.protectionLevel != protectionLevel) {
4295                    // If we return different protection level, don't use the cached info
4296                    if (p.perm != null && p.perm.info == permissionInfo) {
4297                        permissionInfo = new PermissionInfo(permissionInfo);
4298                    }
4299                    permissionInfo.protectionLevel = protectionLevel;
4300                }
4301            }
4302            return permissionInfo;
4303        }
4304    }
4305
4306    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4307            String packageName, int uid) {
4308        // Signature permission flags area always reported
4309        final int protectionLevelMasked = protectionLevel
4310                & (PermissionInfo.PROTECTION_NORMAL
4311                | PermissionInfo.PROTECTION_DANGEROUS
4312                | PermissionInfo.PROTECTION_SIGNATURE);
4313        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4314            return protectionLevel;
4315        }
4316
4317        // System sees all flags.
4318        final int appId = UserHandle.getAppId(uid);
4319        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4320                || appId == Process.SHELL_UID) {
4321            return protectionLevel;
4322        }
4323
4324        // Normalize package name to handle renamed packages and static libs
4325        packageName = resolveInternalPackageNameLPr(packageName,
4326                PackageManager.VERSION_CODE_HIGHEST);
4327
4328        // Apps that target O see flags for all protection levels.
4329        final PackageSetting ps = mSettings.mPackages.get(packageName);
4330        if (ps == null) {
4331            return protectionLevel;
4332        }
4333        if (ps.appId != appId) {
4334            return protectionLevel;
4335        }
4336
4337        final PackageParser.Package pkg = mPackages.get(packageName);
4338        if (pkg == null) {
4339            return protectionLevel;
4340        }
4341        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4342            return protectionLevelMasked;
4343        }
4344
4345        return protectionLevel;
4346    }
4347
4348    @Override
4349    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4350            int flags) {
4351        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4352            return null;
4353        }
4354        // reader
4355        synchronized (mPackages) {
4356            if (group != null && !mPermissionGroups.containsKey(group)) {
4357                // This is thrown as NameNotFoundException
4358                return null;
4359            }
4360
4361            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4362            for (BasePermission p : mSettings.mPermissions.values()) {
4363                if (group == null) {
4364                    if (p.perm == null || p.perm.info.group == null) {
4365                        out.add(generatePermissionInfo(p, flags));
4366                    }
4367                } else {
4368                    if (p.perm != null && group.equals(p.perm.info.group)) {
4369                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4370                    }
4371                }
4372            }
4373            return new ParceledListSlice<>(out);
4374        }
4375    }
4376
4377    @Override
4378    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4379        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4380            return null;
4381        }
4382        // reader
4383        synchronized (mPackages) {
4384            return PackageParser.generatePermissionGroupInfo(
4385                    mPermissionGroups.get(name), flags);
4386        }
4387    }
4388
4389    @Override
4390    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4391        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4392            return ParceledListSlice.emptyList();
4393        }
4394        // reader
4395        synchronized (mPackages) {
4396            final int N = mPermissionGroups.size();
4397            ArrayList<PermissionGroupInfo> out
4398                    = new ArrayList<PermissionGroupInfo>(N);
4399            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4400                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4401            }
4402            return new ParceledListSlice<>(out);
4403        }
4404    }
4405
4406    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4407            int filterCallingUid, int userId) {
4408        if (!sUserManager.exists(userId)) return null;
4409        PackageSetting ps = mSettings.mPackages.get(packageName);
4410        if (ps != null) {
4411            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4412                return null;
4413            }
4414            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4415                return null;
4416            }
4417            if (ps.pkg == null) {
4418                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4419                if (pInfo != null) {
4420                    return pInfo.applicationInfo;
4421                }
4422                return null;
4423            }
4424            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4425                    ps.readUserState(userId), userId);
4426            if (ai != null) {
4427                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4428            }
4429            return ai;
4430        }
4431        return null;
4432    }
4433
4434    @Override
4435    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4436        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4437    }
4438
4439    /**
4440     * Important: The provided filterCallingUid is used exclusively to filter out applications
4441     * that can be seen based on user state. It's typically the original caller uid prior
4442     * to clearing. Because it can only be provided by trusted code, it's value can be
4443     * trusted and will be used as-is; unlike userId which will be validated by this method.
4444     */
4445    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4446            int filterCallingUid, int userId) {
4447        if (!sUserManager.exists(userId)) return null;
4448        flags = updateFlagsForApplication(flags, userId, packageName);
4449        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4450                false /* requireFullPermission */, false /* checkShell */, "get application info");
4451
4452        // writer
4453        synchronized (mPackages) {
4454            // Normalize package name to handle renamed packages and static libs
4455            packageName = resolveInternalPackageNameLPr(packageName,
4456                    PackageManager.VERSION_CODE_HIGHEST);
4457
4458            PackageParser.Package p = mPackages.get(packageName);
4459            if (DEBUG_PACKAGE_INFO) Log.v(
4460                    TAG, "getApplicationInfo " + packageName
4461                    + ": " + p);
4462            if (p != null) {
4463                PackageSetting ps = mSettings.mPackages.get(packageName);
4464                if (ps == null) return null;
4465                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4466                    return null;
4467                }
4468                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4469                    return null;
4470                }
4471                // Note: isEnabledLP() does not apply here - always return info
4472                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4473                        p, flags, ps.readUserState(userId), userId);
4474                if (ai != null) {
4475                    ai.packageName = resolveExternalPackageNameLPr(p);
4476                }
4477                return ai;
4478            }
4479            if ("android".equals(packageName)||"system".equals(packageName)) {
4480                return mAndroidApplication;
4481            }
4482            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4483                // Already generates the external package name
4484                return generateApplicationInfoFromSettingsLPw(packageName,
4485                        flags, filterCallingUid, userId);
4486            }
4487        }
4488        return null;
4489    }
4490
4491    private String normalizePackageNameLPr(String packageName) {
4492        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4493        return normalizedPackageName != null ? normalizedPackageName : packageName;
4494    }
4495
4496    @Override
4497    public void deletePreloadsFileCache() {
4498        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4499            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4500        }
4501        File dir = Environment.getDataPreloadsFileCacheDirectory();
4502        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4503        FileUtils.deleteContents(dir);
4504    }
4505
4506    @Override
4507    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4508            final int storageFlags, final IPackageDataObserver observer) {
4509        mContext.enforceCallingOrSelfPermission(
4510                android.Manifest.permission.CLEAR_APP_CACHE, null);
4511        mHandler.post(() -> {
4512            boolean success = false;
4513            try {
4514                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4515                success = true;
4516            } catch (IOException e) {
4517                Slog.w(TAG, e);
4518            }
4519            if (observer != null) {
4520                try {
4521                    observer.onRemoveCompleted(null, success);
4522                } catch (RemoteException e) {
4523                    Slog.w(TAG, e);
4524                }
4525            }
4526        });
4527    }
4528
4529    @Override
4530    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4531            final int storageFlags, final IntentSender pi) {
4532        mContext.enforceCallingOrSelfPermission(
4533                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4534        mHandler.post(() -> {
4535            boolean success = false;
4536            try {
4537                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4538                success = true;
4539            } catch (IOException e) {
4540                Slog.w(TAG, e);
4541            }
4542            if (pi != null) {
4543                try {
4544                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4545                } catch (SendIntentException e) {
4546                    Slog.w(TAG, e);
4547                }
4548            }
4549        });
4550    }
4551
4552    /**
4553     * Blocking call to clear various types of cached data across the system
4554     * until the requested bytes are available.
4555     */
4556    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4557        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4558        final File file = storage.findPathForUuid(volumeUuid);
4559        if (file.getUsableSpace() >= bytes) return;
4560
4561        if (ENABLE_FREE_CACHE_V2) {
4562            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4563                    volumeUuid);
4564            final boolean aggressive = (storageFlags
4565                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4566            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4567
4568            // 1. Pre-flight to determine if we have any chance to succeed
4569            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4570            if (internalVolume && (aggressive || SystemProperties
4571                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4572                deletePreloadsFileCache();
4573                if (file.getUsableSpace() >= bytes) return;
4574            }
4575
4576            // 3. Consider parsed APK data (aggressive only)
4577            if (internalVolume && aggressive) {
4578                FileUtils.deleteContents(mCacheDir);
4579                if (file.getUsableSpace() >= bytes) return;
4580            }
4581
4582            // 4. Consider cached app data (above quotas)
4583            try {
4584                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4585                        Installer.FLAG_FREE_CACHE_V2);
4586            } catch (InstallerException ignored) {
4587            }
4588            if (file.getUsableSpace() >= bytes) return;
4589
4590            // 5. Consider shared libraries with refcount=0 and age>min cache period
4591            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4592                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4593                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4594                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4595                return;
4596            }
4597
4598            // 6. Consider dexopt output (aggressive only)
4599            // TODO: Implement
4600
4601            // 7. Consider installed instant apps unused longer than min cache period
4602            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4603                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4604                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4605                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4606                return;
4607            }
4608
4609            // 8. Consider cached app data (below quotas)
4610            try {
4611                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4612                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4613            } catch (InstallerException ignored) {
4614            }
4615            if (file.getUsableSpace() >= bytes) return;
4616
4617            // 9. Consider DropBox entries
4618            // TODO: Implement
4619
4620            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4621            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4622                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4623                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4624                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4625                return;
4626            }
4627        } else {
4628            try {
4629                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4630            } catch (InstallerException ignored) {
4631            }
4632            if (file.getUsableSpace() >= bytes) return;
4633        }
4634
4635        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4636    }
4637
4638    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4639            throws IOException {
4640        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4641        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4642
4643        List<VersionedPackage> packagesToDelete = null;
4644        final long now = System.currentTimeMillis();
4645
4646        synchronized (mPackages) {
4647            final int[] allUsers = sUserManager.getUserIds();
4648            final int libCount = mSharedLibraries.size();
4649            for (int i = 0; i < libCount; i++) {
4650                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4651                if (versionedLib == null) {
4652                    continue;
4653                }
4654                final int versionCount = versionedLib.size();
4655                for (int j = 0; j < versionCount; j++) {
4656                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4657                    // Skip packages that are not static shared libs.
4658                    if (!libInfo.isStatic()) {
4659                        break;
4660                    }
4661                    // Important: We skip static shared libs used for some user since
4662                    // in such a case we need to keep the APK on the device. The check for
4663                    // a lib being used for any user is performed by the uninstall call.
4664                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4665                    // Resolve the package name - we use synthetic package names internally
4666                    final String internalPackageName = resolveInternalPackageNameLPr(
4667                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4668                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4669                    // Skip unused static shared libs cached less than the min period
4670                    // to prevent pruning a lib needed by a subsequently installed package.
4671                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4672                        continue;
4673                    }
4674                    if (packagesToDelete == null) {
4675                        packagesToDelete = new ArrayList<>();
4676                    }
4677                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4678                            declaringPackage.getVersionCode()));
4679                }
4680            }
4681        }
4682
4683        if (packagesToDelete != null) {
4684            final int packageCount = packagesToDelete.size();
4685            for (int i = 0; i < packageCount; i++) {
4686                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4687                // Delete the package synchronously (will fail of the lib used for any user).
4688                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4689                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4690                                == PackageManager.DELETE_SUCCEEDED) {
4691                    if (volume.getUsableSpace() >= neededSpace) {
4692                        return true;
4693                    }
4694                }
4695            }
4696        }
4697
4698        return false;
4699    }
4700
4701    /**
4702     * Update given flags based on encryption status of current user.
4703     */
4704    private int updateFlags(int flags, int userId) {
4705        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4706                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4707            // Caller expressed an explicit opinion about what encryption
4708            // aware/unaware components they want to see, so fall through and
4709            // give them what they want
4710        } else {
4711            // Caller expressed no opinion, so match based on user state
4712            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4713                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4714            } else {
4715                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4716            }
4717        }
4718        return flags;
4719    }
4720
4721    private UserManagerInternal getUserManagerInternal() {
4722        if (mUserManagerInternal == null) {
4723            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4724        }
4725        return mUserManagerInternal;
4726    }
4727
4728    private DeviceIdleController.LocalService getDeviceIdleController() {
4729        if (mDeviceIdleController == null) {
4730            mDeviceIdleController =
4731                    LocalServices.getService(DeviceIdleController.LocalService.class);
4732        }
4733        return mDeviceIdleController;
4734    }
4735
4736    /**
4737     * Update given flags when being used to request {@link PackageInfo}.
4738     */
4739    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4740        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4741        boolean triaged = true;
4742        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4743                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4744            // Caller is asking for component details, so they'd better be
4745            // asking for specific encryption matching behavior, or be triaged
4746            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4747                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4748                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4749                triaged = false;
4750            }
4751        }
4752        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4753                | PackageManager.MATCH_SYSTEM_ONLY
4754                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4755            triaged = false;
4756        }
4757        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4758            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4759                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4760                    + Debug.getCallers(5));
4761        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4762                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4763            // If the caller wants all packages and has a restricted profile associated with it,
4764            // then match all users. This is to make sure that launchers that need to access work
4765            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4766            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4767            flags |= PackageManager.MATCH_ANY_USER;
4768        }
4769        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4770            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4771                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4772        }
4773        return updateFlags(flags, userId);
4774    }
4775
4776    /**
4777     * Update given flags when being used to request {@link ApplicationInfo}.
4778     */
4779    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4780        return updateFlagsForPackage(flags, userId, cookie);
4781    }
4782
4783    /**
4784     * Update given flags when being used to request {@link ComponentInfo}.
4785     */
4786    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4787        if (cookie instanceof Intent) {
4788            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4789                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4790            }
4791        }
4792
4793        boolean triaged = true;
4794        // Caller is asking for component details, so they'd better be
4795        // asking for specific encryption matching behavior, or be triaged
4796        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4797                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4798                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4799            triaged = false;
4800        }
4801        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4802            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4803                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4804        }
4805
4806        return updateFlags(flags, userId);
4807    }
4808
4809    /**
4810     * Update given intent when being used to request {@link ResolveInfo}.
4811     */
4812    private Intent updateIntentForResolve(Intent intent) {
4813        if (intent.getSelector() != null) {
4814            intent = intent.getSelector();
4815        }
4816        if (DEBUG_PREFERRED) {
4817            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4818        }
4819        return intent;
4820    }
4821
4822    /**
4823     * Update given flags when being used to request {@link ResolveInfo}.
4824     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4825     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4826     * flag set. However, this flag is only honoured in three circumstances:
4827     * <ul>
4828     * <li>when called from a system process</li>
4829     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4830     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4831     * action and a {@code android.intent.category.BROWSABLE} category</li>
4832     * </ul>
4833     */
4834    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4835        return updateFlagsForResolve(flags, userId, intent, callingUid,
4836                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4837    }
4838    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4839            boolean wantInstantApps) {
4840        return updateFlagsForResolve(flags, userId, intent, callingUid,
4841                wantInstantApps, false /*onlyExposedExplicitly*/);
4842    }
4843    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4844            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4845        // Safe mode means we shouldn't match any third-party components
4846        if (mSafeMode) {
4847            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4848        }
4849        if (getInstantAppPackageName(callingUid) != null) {
4850            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4851            if (onlyExposedExplicitly) {
4852                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4853            }
4854            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4855            flags |= PackageManager.MATCH_INSTANT;
4856        } else {
4857            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4858            final boolean allowMatchInstant =
4859                    (wantInstantApps
4860                            && Intent.ACTION_VIEW.equals(intent.getAction())
4861                            && hasWebURI(intent))
4862                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4863            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4864                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4865            if (!allowMatchInstant) {
4866                flags &= ~PackageManager.MATCH_INSTANT;
4867            }
4868        }
4869        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4870    }
4871
4872    @Override
4873    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4874        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4875    }
4876
4877    /**
4878     * Important: The provided filterCallingUid is used exclusively to filter out activities
4879     * that can be seen based on user state. It's typically the original caller uid prior
4880     * to clearing. Because it can only be provided by trusted code, it's value can be
4881     * trusted and will be used as-is; unlike userId which will be validated by this method.
4882     */
4883    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4884            int filterCallingUid, int userId) {
4885        if (!sUserManager.exists(userId)) return null;
4886        flags = updateFlagsForComponent(flags, userId, component);
4887        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4888                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4889        synchronized (mPackages) {
4890            PackageParser.Activity a = mActivities.mActivities.get(component);
4891
4892            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + 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, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4897                    return null;
4898                }
4899                return PackageParser.generateActivityInfo(
4900                        a, flags, ps.readUserState(userId), userId);
4901            }
4902            if (mResolveComponentName.equals(component)) {
4903                return PackageParser.generateActivityInfo(
4904                        mResolveActivity, flags, new PackageUserState(), userId);
4905            }
4906        }
4907        return null;
4908    }
4909
4910    @Override
4911    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4912            String resolvedType) {
4913        synchronized (mPackages) {
4914            if (component.equals(mResolveComponentName)) {
4915                // The resolver supports EVERYTHING!
4916                return true;
4917            }
4918            final int callingUid = Binder.getCallingUid();
4919            final int callingUserId = UserHandle.getUserId(callingUid);
4920            PackageParser.Activity a = mActivities.mActivities.get(component);
4921            if (a == null) {
4922                return false;
4923            }
4924            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4925            if (ps == null) {
4926                return false;
4927            }
4928            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4929                return false;
4930            }
4931            for (int i=0; i<a.intents.size(); i++) {
4932                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4933                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4934                    return true;
4935                }
4936            }
4937            return false;
4938        }
4939    }
4940
4941    @Override
4942    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4943        if (!sUserManager.exists(userId)) return null;
4944        final int callingUid = Binder.getCallingUid();
4945        flags = updateFlagsForComponent(flags, userId, component);
4946        enforceCrossUserPermission(callingUid, userId,
4947                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4948        synchronized (mPackages) {
4949            PackageParser.Activity a = mReceivers.mActivities.get(component);
4950            if (DEBUG_PACKAGE_INFO) Log.v(
4951                TAG, "getReceiverInfo " + component + ": " + a);
4952            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4953                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4954                if (ps == null) return null;
4955                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4956                    return null;
4957                }
4958                return PackageParser.generateActivityInfo(
4959                        a, flags, ps.readUserState(userId), userId);
4960            }
4961        }
4962        return null;
4963    }
4964
4965    @Override
4966    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4967            int flags, int userId) {
4968        if (!sUserManager.exists(userId)) return null;
4969        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4970        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4971            return null;
4972        }
4973
4974        flags = updateFlagsForPackage(flags, userId, null);
4975
4976        final boolean canSeeStaticLibraries =
4977                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4978                        == PERMISSION_GRANTED
4979                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4980                        == PERMISSION_GRANTED
4981                || canRequestPackageInstallsInternal(packageName,
4982                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4983                        false  /* throwIfPermNotDeclared*/)
4984                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4985                        == PERMISSION_GRANTED;
4986
4987        synchronized (mPackages) {
4988            List<SharedLibraryInfo> result = null;
4989
4990            final int libCount = mSharedLibraries.size();
4991            for (int i = 0; i < libCount; i++) {
4992                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4993                if (versionedLib == null) {
4994                    continue;
4995                }
4996
4997                final int versionCount = versionedLib.size();
4998                for (int j = 0; j < versionCount; j++) {
4999                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5000                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5001                        break;
5002                    }
5003                    final long identity = Binder.clearCallingIdentity();
5004                    try {
5005                        PackageInfo packageInfo = getPackageInfoVersioned(
5006                                libInfo.getDeclaringPackage(), flags
5007                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5008                        if (packageInfo == null) {
5009                            continue;
5010                        }
5011                    } finally {
5012                        Binder.restoreCallingIdentity(identity);
5013                    }
5014
5015                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5016                            libInfo.getVersion(), libInfo.getType(),
5017                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5018                            flags, userId));
5019
5020                    if (result == null) {
5021                        result = new ArrayList<>();
5022                    }
5023                    result.add(resLibInfo);
5024                }
5025            }
5026
5027            return result != null ? new ParceledListSlice<>(result) : null;
5028        }
5029    }
5030
5031    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5032            SharedLibraryInfo libInfo, int flags, int userId) {
5033        List<VersionedPackage> versionedPackages = null;
5034        final int packageCount = mSettings.mPackages.size();
5035        for (int i = 0; i < packageCount; i++) {
5036            PackageSetting ps = mSettings.mPackages.valueAt(i);
5037
5038            if (ps == null) {
5039                continue;
5040            }
5041
5042            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5043                continue;
5044            }
5045
5046            final String libName = libInfo.getName();
5047            if (libInfo.isStatic()) {
5048                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5049                if (libIdx < 0) {
5050                    continue;
5051                }
5052                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5053                    continue;
5054                }
5055                if (versionedPackages == null) {
5056                    versionedPackages = new ArrayList<>();
5057                }
5058                // If the dependent is a static shared lib, use the public package name
5059                String dependentPackageName = ps.name;
5060                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5061                    dependentPackageName = ps.pkg.manifestPackageName;
5062                }
5063                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5064            } else if (ps.pkg != null) {
5065                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5066                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5067                    if (versionedPackages == null) {
5068                        versionedPackages = new ArrayList<>();
5069                    }
5070                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5071                }
5072            }
5073        }
5074
5075        return versionedPackages;
5076    }
5077
5078    @Override
5079    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5080        if (!sUserManager.exists(userId)) return null;
5081        final int callingUid = Binder.getCallingUid();
5082        flags = updateFlagsForComponent(flags, userId, component);
5083        enforceCrossUserPermission(callingUid, userId,
5084                false /* requireFullPermission */, false /* checkShell */, "get service info");
5085        synchronized (mPackages) {
5086            PackageParser.Service s = mServices.mServices.get(component);
5087            if (DEBUG_PACKAGE_INFO) Log.v(
5088                TAG, "getServiceInfo " + component + ": " + s);
5089            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5090                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5091                if (ps == null) return null;
5092                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5093                    return null;
5094                }
5095                return PackageParser.generateServiceInfo(
5096                        s, flags, ps.readUserState(userId), userId);
5097            }
5098        }
5099        return null;
5100    }
5101
5102    @Override
5103    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5104        if (!sUserManager.exists(userId)) return null;
5105        final int callingUid = Binder.getCallingUid();
5106        flags = updateFlagsForComponent(flags, userId, component);
5107        enforceCrossUserPermission(callingUid, userId,
5108                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5109        synchronized (mPackages) {
5110            PackageParser.Provider p = mProviders.mProviders.get(component);
5111            if (DEBUG_PACKAGE_INFO) Log.v(
5112                TAG, "getProviderInfo " + component + ": " + p);
5113            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5114                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5115                if (ps == null) return null;
5116                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5117                    return null;
5118                }
5119                return PackageParser.generateProviderInfo(
5120                        p, flags, ps.readUserState(userId), userId);
5121            }
5122        }
5123        return null;
5124    }
5125
5126    @Override
5127    public String[] getSystemSharedLibraryNames() {
5128        // allow instant applications
5129        synchronized (mPackages) {
5130            Set<String> libs = null;
5131            final int libCount = mSharedLibraries.size();
5132            for (int i = 0; i < libCount; i++) {
5133                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5134                if (versionedLib == null) {
5135                    continue;
5136                }
5137                final int versionCount = versionedLib.size();
5138                for (int j = 0; j < versionCount; j++) {
5139                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5140                    if (!libEntry.info.isStatic()) {
5141                        if (libs == null) {
5142                            libs = new ArraySet<>();
5143                        }
5144                        libs.add(libEntry.info.getName());
5145                        break;
5146                    }
5147                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5148                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5149                            UserHandle.getUserId(Binder.getCallingUid()),
5150                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5151                        if (libs == null) {
5152                            libs = new ArraySet<>();
5153                        }
5154                        libs.add(libEntry.info.getName());
5155                        break;
5156                    }
5157                }
5158            }
5159
5160            if (libs != null) {
5161                String[] libsArray = new String[libs.size()];
5162                libs.toArray(libsArray);
5163                return libsArray;
5164            }
5165
5166            return null;
5167        }
5168    }
5169
5170    @Override
5171    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5172        // allow instant applications
5173        synchronized (mPackages) {
5174            return mServicesSystemSharedLibraryPackageName;
5175        }
5176    }
5177
5178    @Override
5179    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5180        // allow instant applications
5181        synchronized (mPackages) {
5182            return mSharedSystemSharedLibraryPackageName;
5183        }
5184    }
5185
5186    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5187        for (int i = userList.length - 1; i >= 0; --i) {
5188            final int userId = userList[i];
5189            // don't add instant app to the list of updates
5190            if (pkgSetting.getInstantApp(userId)) {
5191                continue;
5192            }
5193            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5194            if (changedPackages == null) {
5195                changedPackages = new SparseArray<>();
5196                mChangedPackages.put(userId, changedPackages);
5197            }
5198            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5199            if (sequenceNumbers == null) {
5200                sequenceNumbers = new HashMap<>();
5201                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5202            }
5203            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5204            if (sequenceNumber != null) {
5205                changedPackages.remove(sequenceNumber);
5206            }
5207            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5208            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5209        }
5210        mChangedPackagesSequenceNumber++;
5211    }
5212
5213    @Override
5214    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5215        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5216            return null;
5217        }
5218        synchronized (mPackages) {
5219            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5220                return null;
5221            }
5222            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5223            if (changedPackages == null) {
5224                return null;
5225            }
5226            final List<String> packageNames =
5227                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5228            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5229                final String packageName = changedPackages.get(i);
5230                if (packageName != null) {
5231                    packageNames.add(packageName);
5232                }
5233            }
5234            return packageNames.isEmpty()
5235                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5236        }
5237    }
5238
5239    @Override
5240    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5241        // allow instant applications
5242        ArrayList<FeatureInfo> res;
5243        synchronized (mAvailableFeatures) {
5244            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5245            res.addAll(mAvailableFeatures.values());
5246        }
5247        final FeatureInfo fi = new FeatureInfo();
5248        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5249                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5250        res.add(fi);
5251
5252        return new ParceledListSlice<>(res);
5253    }
5254
5255    @Override
5256    public boolean hasSystemFeature(String name, int version) {
5257        // allow instant applications
5258        synchronized (mAvailableFeatures) {
5259            final FeatureInfo feat = mAvailableFeatures.get(name);
5260            if (feat == null) {
5261                return false;
5262            } else {
5263                return feat.version >= version;
5264            }
5265        }
5266    }
5267
5268    @Override
5269    public int checkPermission(String permName, String pkgName, int userId) {
5270        if (!sUserManager.exists(userId)) {
5271            return PackageManager.PERMISSION_DENIED;
5272        }
5273        final int callingUid = Binder.getCallingUid();
5274
5275        synchronized (mPackages) {
5276            final PackageParser.Package p = mPackages.get(pkgName);
5277            if (p != null && p.mExtras != null) {
5278                final PackageSetting ps = (PackageSetting) p.mExtras;
5279                if (filterAppAccessLPr(ps, callingUid, userId)) {
5280                    return PackageManager.PERMISSION_DENIED;
5281                }
5282                final boolean instantApp = ps.getInstantApp(userId);
5283                final PermissionsState permissionsState = ps.getPermissionsState();
5284                if (permissionsState.hasPermission(permName, userId)) {
5285                    if (instantApp) {
5286                        BasePermission bp = mSettings.mPermissions.get(permName);
5287                        if (bp != null && bp.isInstant()) {
5288                            return PackageManager.PERMISSION_GRANTED;
5289                        }
5290                    } else {
5291                        return PackageManager.PERMISSION_GRANTED;
5292                    }
5293                }
5294                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5295                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5296                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5297                    return PackageManager.PERMISSION_GRANTED;
5298                }
5299            }
5300        }
5301
5302        return PackageManager.PERMISSION_DENIED;
5303    }
5304
5305    @Override
5306    public int checkUidPermission(String permName, int uid) {
5307        final int callingUid = Binder.getCallingUid();
5308        final int callingUserId = UserHandle.getUserId(callingUid);
5309        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5310        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5311        final int userId = UserHandle.getUserId(uid);
5312        if (!sUserManager.exists(userId)) {
5313            return PackageManager.PERMISSION_DENIED;
5314        }
5315
5316        synchronized (mPackages) {
5317            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5318            if (obj != null) {
5319                if (obj instanceof SharedUserSetting) {
5320                    if (isCallerInstantApp) {
5321                        return PackageManager.PERMISSION_DENIED;
5322                    }
5323                } else if (obj instanceof PackageSetting) {
5324                    final PackageSetting ps = (PackageSetting) obj;
5325                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5326                        return PackageManager.PERMISSION_DENIED;
5327                    }
5328                }
5329                final SettingBase settingBase = (SettingBase) obj;
5330                final PermissionsState permissionsState = settingBase.getPermissionsState();
5331                if (permissionsState.hasPermission(permName, userId)) {
5332                    if (isUidInstantApp) {
5333                        BasePermission bp = mSettings.mPermissions.get(permName);
5334                        if (bp != null && bp.isInstant()) {
5335                            return PackageManager.PERMISSION_GRANTED;
5336                        }
5337                    } else {
5338                        return PackageManager.PERMISSION_GRANTED;
5339                    }
5340                }
5341                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5342                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5343                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5344                    return PackageManager.PERMISSION_GRANTED;
5345                }
5346            } else {
5347                ArraySet<String> perms = mSystemPermissions.get(uid);
5348                if (perms != null) {
5349                    if (perms.contains(permName)) {
5350                        return PackageManager.PERMISSION_GRANTED;
5351                    }
5352                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5353                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5354                        return PackageManager.PERMISSION_GRANTED;
5355                    }
5356                }
5357            }
5358        }
5359
5360        return PackageManager.PERMISSION_DENIED;
5361    }
5362
5363    @Override
5364    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5365        if (UserHandle.getCallingUserId() != userId) {
5366            mContext.enforceCallingPermission(
5367                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5368                    "isPermissionRevokedByPolicy for user " + userId);
5369        }
5370
5371        if (checkPermission(permission, packageName, userId)
5372                == PackageManager.PERMISSION_GRANTED) {
5373            return false;
5374        }
5375
5376        final int callingUid = Binder.getCallingUid();
5377        if (getInstantAppPackageName(callingUid) != null) {
5378            if (!isCallerSameApp(packageName, callingUid)) {
5379                return false;
5380            }
5381        } else {
5382            if (isInstantApp(packageName, userId)) {
5383                return false;
5384            }
5385        }
5386
5387        final long identity = Binder.clearCallingIdentity();
5388        try {
5389            final int flags = getPermissionFlags(permission, packageName, userId);
5390            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5391        } finally {
5392            Binder.restoreCallingIdentity(identity);
5393        }
5394    }
5395
5396    @Override
5397    public String getPermissionControllerPackageName() {
5398        synchronized (mPackages) {
5399            return mRequiredInstallerPackage;
5400        }
5401    }
5402
5403    /**
5404     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5405     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5406     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5407     * @param message the message to log on security exception
5408     */
5409    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5410            boolean checkShell, String message) {
5411        if (userId < 0) {
5412            throw new IllegalArgumentException("Invalid userId " + userId);
5413        }
5414        if (checkShell) {
5415            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5416        }
5417        if (userId == UserHandle.getUserId(callingUid)) return;
5418        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5419            if (requireFullPermission) {
5420                mContext.enforceCallingOrSelfPermission(
5421                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5422            } else {
5423                try {
5424                    mContext.enforceCallingOrSelfPermission(
5425                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5426                } catch (SecurityException se) {
5427                    mContext.enforceCallingOrSelfPermission(
5428                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5429                }
5430            }
5431        }
5432    }
5433
5434    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5435        if (callingUid == Process.SHELL_UID) {
5436            if (userHandle >= 0
5437                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5438                throw new SecurityException("Shell does not have permission to access user "
5439                        + userHandle);
5440            } else if (userHandle < 0) {
5441                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5442                        + Debug.getCallers(3));
5443            }
5444        }
5445    }
5446
5447    private BasePermission findPermissionTreeLP(String permName) {
5448        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5449            if (permName.startsWith(bp.name) &&
5450                    permName.length() > bp.name.length() &&
5451                    permName.charAt(bp.name.length()) == '.') {
5452                return bp;
5453            }
5454        }
5455        return null;
5456    }
5457
5458    private BasePermission checkPermissionTreeLP(String permName) {
5459        if (permName != null) {
5460            BasePermission bp = findPermissionTreeLP(permName);
5461            if (bp != null) {
5462                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5463                    return bp;
5464                }
5465                throw new SecurityException("Calling uid "
5466                        + Binder.getCallingUid()
5467                        + " is not allowed to add to permission tree "
5468                        + bp.name + " owned by uid " + bp.uid);
5469            }
5470        }
5471        throw new SecurityException("No permission tree found for " + permName);
5472    }
5473
5474    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5475        if (s1 == null) {
5476            return s2 == null;
5477        }
5478        if (s2 == null) {
5479            return false;
5480        }
5481        if (s1.getClass() != s2.getClass()) {
5482            return false;
5483        }
5484        return s1.equals(s2);
5485    }
5486
5487    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5488        if (pi1.icon != pi2.icon) return false;
5489        if (pi1.logo != pi2.logo) return false;
5490        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5491        if (!compareStrings(pi1.name, pi2.name)) return false;
5492        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5493        // We'll take care of setting this one.
5494        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5495        // These are not currently stored in settings.
5496        //if (!compareStrings(pi1.group, pi2.group)) return false;
5497        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5498        //if (pi1.labelRes != pi2.labelRes) return false;
5499        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5500        return true;
5501    }
5502
5503    int permissionInfoFootprint(PermissionInfo info) {
5504        int size = info.name.length();
5505        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5506        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5507        return size;
5508    }
5509
5510    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5511        int size = 0;
5512        for (BasePermission perm : mSettings.mPermissions.values()) {
5513            if (perm.uid == tree.uid) {
5514                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5515            }
5516        }
5517        return size;
5518    }
5519
5520    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5521        // We calculate the max size of permissions defined by this uid and throw
5522        // if that plus the size of 'info' would exceed our stated maximum.
5523        if (tree.uid != Process.SYSTEM_UID) {
5524            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5525            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5526                throw new SecurityException("Permission tree size cap exceeded");
5527            }
5528        }
5529    }
5530
5531    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5532        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5533            throw new SecurityException("Instant apps can't add permissions");
5534        }
5535        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5536            throw new SecurityException("Label must be specified in permission");
5537        }
5538        BasePermission tree = checkPermissionTreeLP(info.name);
5539        BasePermission bp = mSettings.mPermissions.get(info.name);
5540        boolean added = bp == null;
5541        boolean changed = true;
5542        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5543        if (added) {
5544            enforcePermissionCapLocked(info, tree);
5545            bp = new BasePermission(info.name, tree.sourcePackage,
5546                    BasePermission.TYPE_DYNAMIC);
5547        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5548            throw new SecurityException(
5549                    "Not allowed to modify non-dynamic permission "
5550                    + info.name);
5551        } else {
5552            if (bp.protectionLevel == fixedLevel
5553                    && bp.perm.owner.equals(tree.perm.owner)
5554                    && bp.uid == tree.uid
5555                    && comparePermissionInfos(bp.perm.info, info)) {
5556                changed = false;
5557            }
5558        }
5559        bp.protectionLevel = fixedLevel;
5560        info = new PermissionInfo(info);
5561        info.protectionLevel = fixedLevel;
5562        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5563        bp.perm.info.packageName = tree.perm.info.packageName;
5564        bp.uid = tree.uid;
5565        if (added) {
5566            mSettings.mPermissions.put(info.name, bp);
5567        }
5568        if (changed) {
5569            if (!async) {
5570                mSettings.writeLPr();
5571            } else {
5572                scheduleWriteSettingsLocked();
5573            }
5574        }
5575        return added;
5576    }
5577
5578    @Override
5579    public boolean addPermission(PermissionInfo info) {
5580        synchronized (mPackages) {
5581            return addPermissionLocked(info, false);
5582        }
5583    }
5584
5585    @Override
5586    public boolean addPermissionAsync(PermissionInfo info) {
5587        synchronized (mPackages) {
5588            return addPermissionLocked(info, true);
5589        }
5590    }
5591
5592    @Override
5593    public void removePermission(String name) {
5594        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5595            throw new SecurityException("Instant applications don't have access to this method");
5596        }
5597        synchronized (mPackages) {
5598            checkPermissionTreeLP(name);
5599            BasePermission bp = mSettings.mPermissions.get(name);
5600            if (bp != null) {
5601                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5602                    throw new SecurityException(
5603                            "Not allowed to modify non-dynamic permission "
5604                            + name);
5605                }
5606                mSettings.mPermissions.remove(name);
5607                mSettings.writeLPr();
5608            }
5609        }
5610    }
5611
5612    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5613            PackageParser.Package pkg, BasePermission bp) {
5614        int index = pkg.requestedPermissions.indexOf(bp.name);
5615        if (index == -1) {
5616            throw new SecurityException("Package " + pkg.packageName
5617                    + " has not requested permission " + bp.name);
5618        }
5619        if (!bp.isRuntime() && !bp.isDevelopment()) {
5620            throw new SecurityException("Permission " + bp.name
5621                    + " is not a changeable permission type");
5622        }
5623    }
5624
5625    @Override
5626    public void grantRuntimePermission(String packageName, String name, final int userId) {
5627        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5628    }
5629
5630    private void grantRuntimePermission(String packageName, String name, final int userId,
5631            boolean overridePolicy) {
5632        if (!sUserManager.exists(userId)) {
5633            Log.e(TAG, "No such user:" + userId);
5634            return;
5635        }
5636        final int callingUid = Binder.getCallingUid();
5637
5638        mContext.enforceCallingOrSelfPermission(
5639                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5640                "grantRuntimePermission");
5641
5642        enforceCrossUserPermission(callingUid, userId,
5643                true /* requireFullPermission */, true /* checkShell */,
5644                "grantRuntimePermission");
5645
5646        final int uid;
5647        final PackageSetting ps;
5648
5649        synchronized (mPackages) {
5650            final PackageParser.Package pkg = mPackages.get(packageName);
5651            if (pkg == null) {
5652                throw new IllegalArgumentException("Unknown package: " + packageName);
5653            }
5654            final BasePermission bp = mSettings.mPermissions.get(name);
5655            if (bp == null) {
5656                throw new IllegalArgumentException("Unknown permission: " + name);
5657            }
5658            ps = (PackageSetting) pkg.mExtras;
5659            if (ps == null
5660                    || filterAppAccessLPr(ps, callingUid, userId)) {
5661                throw new IllegalArgumentException("Unknown package: " + packageName);
5662            }
5663
5664            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5665
5666            // If a permission review is required for legacy apps we represent
5667            // their permissions as always granted runtime ones since we need
5668            // to keep the review required permission flag per user while an
5669            // install permission's state is shared across all users.
5670            if (mPermissionReviewRequired
5671                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5672                    && bp.isRuntime()) {
5673                return;
5674            }
5675
5676            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5677
5678            final PermissionsState permissionsState = ps.getPermissionsState();
5679
5680            final int flags = permissionsState.getPermissionFlags(name, userId);
5681            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5682                throw new SecurityException("Cannot grant system fixed permission "
5683                        + name + " for package " + packageName);
5684            }
5685            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5686                throw new SecurityException("Cannot grant policy fixed permission "
5687                        + name + " for package " + packageName);
5688            }
5689
5690            if (bp.isDevelopment()) {
5691                // Development permissions must be handled specially, since they are not
5692                // normal runtime permissions.  For now they apply to all users.
5693                if (permissionsState.grantInstallPermission(bp) !=
5694                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5695                    scheduleWriteSettingsLocked();
5696                }
5697                return;
5698            }
5699
5700            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5701                throw new SecurityException("Cannot grant non-ephemeral permission"
5702                        + name + " for package " + packageName);
5703            }
5704
5705            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5706                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5707                return;
5708            }
5709
5710            final int result = permissionsState.grantRuntimePermission(bp, userId);
5711            switch (result) {
5712                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5713                    return;
5714                }
5715
5716                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5717                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5718                    mHandler.post(new Runnable() {
5719                        @Override
5720                        public void run() {
5721                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5722                        }
5723                    });
5724                }
5725                break;
5726            }
5727
5728            if (bp.isRuntime()) {
5729                logPermissionGranted(mContext, name, packageName);
5730            }
5731
5732            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5733
5734            // Not critical if that is lost - app has to request again.
5735            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5736        }
5737
5738        // Only need to do this if user is initialized. Otherwise it's a new user
5739        // and there are no processes running as the user yet and there's no need
5740        // to make an expensive call to remount processes for the changed permissions.
5741        if (READ_EXTERNAL_STORAGE.equals(name)
5742                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5743            final long token = Binder.clearCallingIdentity();
5744            try {
5745                if (sUserManager.isInitialized(userId)) {
5746                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5747                            StorageManagerInternal.class);
5748                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5749                }
5750            } finally {
5751                Binder.restoreCallingIdentity(token);
5752            }
5753        }
5754    }
5755
5756    @Override
5757    public void revokeRuntimePermission(String packageName, String name, int userId) {
5758        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5759    }
5760
5761    private void revokeRuntimePermission(String packageName, String name, int userId,
5762            boolean overridePolicy) {
5763        if (!sUserManager.exists(userId)) {
5764            Log.e(TAG, "No such user:" + userId);
5765            return;
5766        }
5767
5768        mContext.enforceCallingOrSelfPermission(
5769                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5770                "revokeRuntimePermission");
5771
5772        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5773                true /* requireFullPermission */, true /* checkShell */,
5774                "revokeRuntimePermission");
5775
5776        final int appId;
5777
5778        synchronized (mPackages) {
5779            final PackageParser.Package pkg = mPackages.get(packageName);
5780            if (pkg == null) {
5781                throw new IllegalArgumentException("Unknown package: " + packageName);
5782            }
5783            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5784            if (ps == null
5785                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5786                throw new IllegalArgumentException("Unknown package: " + packageName);
5787            }
5788            final BasePermission bp = mSettings.mPermissions.get(name);
5789            if (bp == null) {
5790                throw new IllegalArgumentException("Unknown permission: " + name);
5791            }
5792
5793            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5794
5795            // If a permission review is required for legacy apps we represent
5796            // their permissions as always granted runtime ones since we need
5797            // to keep the review required permission flag per user while an
5798            // install permission's state is shared across all users.
5799            if (mPermissionReviewRequired
5800                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5801                    && bp.isRuntime()) {
5802                return;
5803            }
5804
5805            final PermissionsState permissionsState = ps.getPermissionsState();
5806
5807            final int flags = permissionsState.getPermissionFlags(name, userId);
5808            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5809                throw new SecurityException("Cannot revoke system fixed permission "
5810                        + name + " for package " + packageName);
5811            }
5812            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5813                throw new SecurityException("Cannot revoke policy fixed permission "
5814                        + name + " for package " + packageName);
5815            }
5816
5817            if (bp.isDevelopment()) {
5818                // Development permissions must be handled specially, since they are not
5819                // normal runtime permissions.  For now they apply to all users.
5820                if (permissionsState.revokeInstallPermission(bp) !=
5821                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5822                    scheduleWriteSettingsLocked();
5823                }
5824                return;
5825            }
5826
5827            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5828                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5829                return;
5830            }
5831
5832            if (bp.isRuntime()) {
5833                logPermissionRevoked(mContext, name, packageName);
5834            }
5835
5836            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5837
5838            // Critical, after this call app should never have the permission.
5839            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5840
5841            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5842        }
5843
5844        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5845    }
5846
5847    /**
5848     * Get the first event id for the permission.
5849     *
5850     * <p>There are four events for each permission: <ul>
5851     *     <li>Request permission: first id + 0</li>
5852     *     <li>Grant permission: first id + 1</li>
5853     *     <li>Request for permission denied: first id + 2</li>
5854     *     <li>Revoke permission: first id + 3</li>
5855     * </ul></p>
5856     *
5857     * @param name name of the permission
5858     *
5859     * @return The first event id for the permission
5860     */
5861    private static int getBaseEventId(@NonNull String name) {
5862        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5863
5864        if (eventIdIndex == -1) {
5865            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5866                    || Build.IS_USER) {
5867                Log.i(TAG, "Unknown permission " + name);
5868
5869                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5870            } else {
5871                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5872                //
5873                // Also update
5874                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5875                // - metrics_constants.proto
5876                throw new IllegalStateException("Unknown permission " + name);
5877            }
5878        }
5879
5880        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5881    }
5882
5883    /**
5884     * Log that a permission was revoked.
5885     *
5886     * @param context Context of the caller
5887     * @param name name of the permission
5888     * @param packageName package permission if for
5889     */
5890    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5891            @NonNull String packageName) {
5892        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5893    }
5894
5895    /**
5896     * Log that a permission request was granted.
5897     *
5898     * @param context Context of the caller
5899     * @param name name of the permission
5900     * @param packageName package permission if for
5901     */
5902    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5903            @NonNull String packageName) {
5904        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5905    }
5906
5907    @Override
5908    public void resetRuntimePermissions() {
5909        mContext.enforceCallingOrSelfPermission(
5910                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5911                "revokeRuntimePermission");
5912
5913        int callingUid = Binder.getCallingUid();
5914        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5915            mContext.enforceCallingOrSelfPermission(
5916                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5917                    "resetRuntimePermissions");
5918        }
5919
5920        synchronized (mPackages) {
5921            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5922            for (int userId : UserManagerService.getInstance().getUserIds()) {
5923                final int packageCount = mPackages.size();
5924                for (int i = 0; i < packageCount; i++) {
5925                    PackageParser.Package pkg = mPackages.valueAt(i);
5926                    if (!(pkg.mExtras instanceof PackageSetting)) {
5927                        continue;
5928                    }
5929                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5930                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5931                }
5932            }
5933        }
5934    }
5935
5936    @Override
5937    public int getPermissionFlags(String name, String packageName, int userId) {
5938        if (!sUserManager.exists(userId)) {
5939            return 0;
5940        }
5941
5942        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5943
5944        final int callingUid = Binder.getCallingUid();
5945        enforceCrossUserPermission(callingUid, userId,
5946                true /* requireFullPermission */, false /* checkShell */,
5947                "getPermissionFlags");
5948
5949        synchronized (mPackages) {
5950            final PackageParser.Package pkg = mPackages.get(packageName);
5951            if (pkg == null) {
5952                return 0;
5953            }
5954            final BasePermission bp = mSettings.mPermissions.get(name);
5955            if (bp == null) {
5956                return 0;
5957            }
5958            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5959            if (ps == null
5960                    || filterAppAccessLPr(ps, callingUid, userId)) {
5961                return 0;
5962            }
5963            PermissionsState permissionsState = ps.getPermissionsState();
5964            return permissionsState.getPermissionFlags(name, userId);
5965        }
5966    }
5967
5968    @Override
5969    public void updatePermissionFlags(String name, String packageName, int flagMask,
5970            int flagValues, int userId) {
5971        if (!sUserManager.exists(userId)) {
5972            return;
5973        }
5974
5975        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5976
5977        final int callingUid = Binder.getCallingUid();
5978        enforceCrossUserPermission(callingUid, userId,
5979                true /* requireFullPermission */, true /* checkShell */,
5980                "updatePermissionFlags");
5981
5982        // Only the system can change these flags and nothing else.
5983        if (getCallingUid() != Process.SYSTEM_UID) {
5984            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5985            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5986            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5987            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5988            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5989        }
5990
5991        synchronized (mPackages) {
5992            final PackageParser.Package pkg = mPackages.get(packageName);
5993            if (pkg == null) {
5994                throw new IllegalArgumentException("Unknown package: " + packageName);
5995            }
5996            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5997            if (ps == null
5998                    || filterAppAccessLPr(ps, callingUid, userId)) {
5999                throw new IllegalArgumentException("Unknown package: " + packageName);
6000            }
6001
6002            final BasePermission bp = mSettings.mPermissions.get(name);
6003            if (bp == null) {
6004                throw new IllegalArgumentException("Unknown permission: " + name);
6005            }
6006
6007            PermissionsState permissionsState = ps.getPermissionsState();
6008
6009            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6010
6011            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6012                // Install and runtime permissions are stored in different places,
6013                // so figure out what permission changed and persist the change.
6014                if (permissionsState.getInstallPermissionState(name) != null) {
6015                    scheduleWriteSettingsLocked();
6016                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6017                        || hadState) {
6018                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6019                }
6020            }
6021        }
6022    }
6023
6024    /**
6025     * Update the permission flags for all packages and runtime permissions of a user in order
6026     * to allow device or profile owner to remove POLICY_FIXED.
6027     */
6028    @Override
6029    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6030        if (!sUserManager.exists(userId)) {
6031            return;
6032        }
6033
6034        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6035
6036        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6037                true /* requireFullPermission */, true /* checkShell */,
6038                "updatePermissionFlagsForAllApps");
6039
6040        // Only the system can change system fixed flags.
6041        if (getCallingUid() != Process.SYSTEM_UID) {
6042            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6043            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6044        }
6045
6046        synchronized (mPackages) {
6047            boolean changed = false;
6048            final int packageCount = mPackages.size();
6049            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6050                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6051                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6052                if (ps == null) {
6053                    continue;
6054                }
6055                PermissionsState permissionsState = ps.getPermissionsState();
6056                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6057                        userId, flagMask, flagValues);
6058            }
6059            if (changed) {
6060                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6061            }
6062        }
6063    }
6064
6065    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6066        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6067                != PackageManager.PERMISSION_GRANTED
6068            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6069                != PackageManager.PERMISSION_GRANTED) {
6070            throw new SecurityException(message + " requires "
6071                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6072                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6073        }
6074    }
6075
6076    @Override
6077    public boolean shouldShowRequestPermissionRationale(String permissionName,
6078            String packageName, int userId) {
6079        if (UserHandle.getCallingUserId() != userId) {
6080            mContext.enforceCallingPermission(
6081                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6082                    "canShowRequestPermissionRationale for user " + userId);
6083        }
6084
6085        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6086        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6087            return false;
6088        }
6089
6090        if (checkPermission(permissionName, packageName, userId)
6091                == PackageManager.PERMISSION_GRANTED) {
6092            return false;
6093        }
6094
6095        final int flags;
6096
6097        final long identity = Binder.clearCallingIdentity();
6098        try {
6099            flags = getPermissionFlags(permissionName,
6100                    packageName, userId);
6101        } finally {
6102            Binder.restoreCallingIdentity(identity);
6103        }
6104
6105        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6106                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6107                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6108
6109        if ((flags & fixedFlags) != 0) {
6110            return false;
6111        }
6112
6113        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6114    }
6115
6116    @Override
6117    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6118        mContext.enforceCallingOrSelfPermission(
6119                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6120                "addOnPermissionsChangeListener");
6121
6122        synchronized (mPackages) {
6123            mOnPermissionChangeListeners.addListenerLocked(listener);
6124        }
6125    }
6126
6127    @Override
6128    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6129        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6130            throw new SecurityException("Instant applications don't have access to this method");
6131        }
6132        synchronized (mPackages) {
6133            mOnPermissionChangeListeners.removeListenerLocked(listener);
6134        }
6135    }
6136
6137    @Override
6138    public boolean isProtectedBroadcast(String actionName) {
6139        // allow instant applications
6140        synchronized (mProtectedBroadcasts) {
6141            if (mProtectedBroadcasts.contains(actionName)) {
6142                return true;
6143            } else if (actionName != null) {
6144                // TODO: remove these terrible hacks
6145                if (actionName.startsWith("android.net.netmon.lingerExpired")
6146                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6147                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6148                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6149                    return true;
6150                }
6151            }
6152        }
6153        return false;
6154    }
6155
6156    @Override
6157    public int checkSignatures(String pkg1, String pkg2) {
6158        synchronized (mPackages) {
6159            final PackageParser.Package p1 = mPackages.get(pkg1);
6160            final PackageParser.Package p2 = mPackages.get(pkg2);
6161            if (p1 == null || p1.mExtras == null
6162                    || p2 == null || p2.mExtras == null) {
6163                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6164            }
6165            final int callingUid = Binder.getCallingUid();
6166            final int callingUserId = UserHandle.getUserId(callingUid);
6167            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6168            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6169            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6170                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6171                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6172            }
6173            return compareSignatures(p1.mSignatures, p2.mSignatures);
6174        }
6175    }
6176
6177    @Override
6178    public int checkUidSignatures(int uid1, int uid2) {
6179        final int callingUid = Binder.getCallingUid();
6180        final int callingUserId = UserHandle.getUserId(callingUid);
6181        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6182        // Map to base uids.
6183        uid1 = UserHandle.getAppId(uid1);
6184        uid2 = UserHandle.getAppId(uid2);
6185        // reader
6186        synchronized (mPackages) {
6187            Signature[] s1;
6188            Signature[] s2;
6189            Object obj = mSettings.getUserIdLPr(uid1);
6190            if (obj != null) {
6191                if (obj instanceof SharedUserSetting) {
6192                    if (isCallerInstantApp) {
6193                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6194                    }
6195                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6196                } else if (obj instanceof PackageSetting) {
6197                    final PackageSetting ps = (PackageSetting) obj;
6198                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6199                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6200                    }
6201                    s1 = ps.signatures.mSignatures;
6202                } else {
6203                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6204                }
6205            } else {
6206                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6207            }
6208            obj = mSettings.getUserIdLPr(uid2);
6209            if (obj != null) {
6210                if (obj instanceof SharedUserSetting) {
6211                    if (isCallerInstantApp) {
6212                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6213                    }
6214                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6215                } else if (obj instanceof PackageSetting) {
6216                    final PackageSetting ps = (PackageSetting) obj;
6217                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6218                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6219                    }
6220                    s2 = ps.signatures.mSignatures;
6221                } else {
6222                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6223                }
6224            } else {
6225                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6226            }
6227            return compareSignatures(s1, s2);
6228        }
6229    }
6230
6231    /**
6232     * This method should typically only be used when granting or revoking
6233     * permissions, since the app may immediately restart after this call.
6234     * <p>
6235     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6236     * guard your work against the app being relaunched.
6237     */
6238    private void killUid(int appId, int userId, String reason) {
6239        final long identity = Binder.clearCallingIdentity();
6240        try {
6241            IActivityManager am = ActivityManager.getService();
6242            if (am != null) {
6243                try {
6244                    am.killUid(appId, userId, reason);
6245                } catch (RemoteException e) {
6246                    /* ignore - same process */
6247                }
6248            }
6249        } finally {
6250            Binder.restoreCallingIdentity(identity);
6251        }
6252    }
6253
6254    /**
6255     * Compares two sets of signatures. Returns:
6256     * <br />
6257     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6258     * <br />
6259     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6260     * <br />
6261     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6262     * <br />
6263     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6264     * <br />
6265     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6266     */
6267    static int compareSignatures(Signature[] s1, Signature[] s2) {
6268        if (s1 == null) {
6269            return s2 == null
6270                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6271                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6272        }
6273
6274        if (s2 == null) {
6275            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6276        }
6277
6278        if (s1.length != s2.length) {
6279            return PackageManager.SIGNATURE_NO_MATCH;
6280        }
6281
6282        // Since both signature sets are of size 1, we can compare without HashSets.
6283        if (s1.length == 1) {
6284            return s1[0].equals(s2[0]) ?
6285                    PackageManager.SIGNATURE_MATCH :
6286                    PackageManager.SIGNATURE_NO_MATCH;
6287        }
6288
6289        ArraySet<Signature> set1 = new ArraySet<Signature>();
6290        for (Signature sig : s1) {
6291            set1.add(sig);
6292        }
6293        ArraySet<Signature> set2 = new ArraySet<Signature>();
6294        for (Signature sig : s2) {
6295            set2.add(sig);
6296        }
6297        // Make sure s2 contains all signatures in s1.
6298        if (set1.equals(set2)) {
6299            return PackageManager.SIGNATURE_MATCH;
6300        }
6301        return PackageManager.SIGNATURE_NO_MATCH;
6302    }
6303
6304    /**
6305     * If the database version for this type of package (internal storage or
6306     * external storage) is less than the version where package signatures
6307     * were updated, return true.
6308     */
6309    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6310        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6311        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6312    }
6313
6314    /**
6315     * Used for backward compatibility to make sure any packages with
6316     * certificate chains get upgraded to the new style. {@code existingSigs}
6317     * will be in the old format (since they were stored on disk from before the
6318     * system upgrade) and {@code scannedSigs} will be in the newer format.
6319     */
6320    private int compareSignaturesCompat(PackageSignatures existingSigs,
6321            PackageParser.Package scannedPkg) {
6322        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6323            return PackageManager.SIGNATURE_NO_MATCH;
6324        }
6325
6326        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6327        for (Signature sig : existingSigs.mSignatures) {
6328            existingSet.add(sig);
6329        }
6330        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6331        for (Signature sig : scannedPkg.mSignatures) {
6332            try {
6333                Signature[] chainSignatures = sig.getChainSignatures();
6334                for (Signature chainSig : chainSignatures) {
6335                    scannedCompatSet.add(chainSig);
6336                }
6337            } catch (CertificateEncodingException e) {
6338                scannedCompatSet.add(sig);
6339            }
6340        }
6341        /*
6342         * Make sure the expanded scanned set contains all signatures in the
6343         * existing one.
6344         */
6345        if (scannedCompatSet.equals(existingSet)) {
6346            // Migrate the old signatures to the new scheme.
6347            existingSigs.assignSignatures(scannedPkg.mSignatures);
6348            // The new KeySets will be re-added later in the scanning process.
6349            synchronized (mPackages) {
6350                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6351            }
6352            return PackageManager.SIGNATURE_MATCH;
6353        }
6354        return PackageManager.SIGNATURE_NO_MATCH;
6355    }
6356
6357    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6358        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6359        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6360    }
6361
6362    private int compareSignaturesRecover(PackageSignatures existingSigs,
6363            PackageParser.Package scannedPkg) {
6364        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6365            return PackageManager.SIGNATURE_NO_MATCH;
6366        }
6367
6368        String msg = null;
6369        try {
6370            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6371                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6372                        + scannedPkg.packageName);
6373                return PackageManager.SIGNATURE_MATCH;
6374            }
6375        } catch (CertificateException e) {
6376            msg = e.getMessage();
6377        }
6378
6379        logCriticalInfo(Log.INFO,
6380                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6381        return PackageManager.SIGNATURE_NO_MATCH;
6382    }
6383
6384    @Override
6385    public List<String> getAllPackages() {
6386        final int callingUid = Binder.getCallingUid();
6387        final int callingUserId = UserHandle.getUserId(callingUid);
6388        synchronized (mPackages) {
6389            if (canViewInstantApps(callingUid, callingUserId)) {
6390                return new ArrayList<String>(mPackages.keySet());
6391            }
6392            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6393            final List<String> result = new ArrayList<>();
6394            if (instantAppPkgName != null) {
6395                // caller is an instant application; filter unexposed applications
6396                for (PackageParser.Package pkg : mPackages.values()) {
6397                    if (!pkg.visibleToInstantApps) {
6398                        continue;
6399                    }
6400                    result.add(pkg.packageName);
6401                }
6402            } else {
6403                // caller is a normal application; filter instant applications
6404                for (PackageParser.Package pkg : mPackages.values()) {
6405                    final PackageSetting ps =
6406                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6407                    if (ps != null
6408                            && ps.getInstantApp(callingUserId)
6409                            && !mInstantAppRegistry.isInstantAccessGranted(
6410                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6411                        continue;
6412                    }
6413                    result.add(pkg.packageName);
6414                }
6415            }
6416            return result;
6417        }
6418    }
6419
6420    @Override
6421    public String[] getPackagesForUid(int uid) {
6422        final int callingUid = Binder.getCallingUid();
6423        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6424        final int userId = UserHandle.getUserId(uid);
6425        uid = UserHandle.getAppId(uid);
6426        // reader
6427        synchronized (mPackages) {
6428            Object obj = mSettings.getUserIdLPr(uid);
6429            if (obj instanceof SharedUserSetting) {
6430                if (isCallerInstantApp) {
6431                    return null;
6432                }
6433                final SharedUserSetting sus = (SharedUserSetting) obj;
6434                final int N = sus.packages.size();
6435                String[] res = new String[N];
6436                final Iterator<PackageSetting> it = sus.packages.iterator();
6437                int i = 0;
6438                while (it.hasNext()) {
6439                    PackageSetting ps = it.next();
6440                    if (ps.getInstalled(userId)) {
6441                        res[i++] = ps.name;
6442                    } else {
6443                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6444                    }
6445                }
6446                return res;
6447            } else if (obj instanceof PackageSetting) {
6448                final PackageSetting ps = (PackageSetting) obj;
6449                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6450                    return new String[]{ps.name};
6451                }
6452            }
6453        }
6454        return null;
6455    }
6456
6457    @Override
6458    public String getNameForUid(int uid) {
6459        final int callingUid = Binder.getCallingUid();
6460        if (getInstantAppPackageName(callingUid) != null) {
6461            return null;
6462        }
6463        synchronized (mPackages) {
6464            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6465            if (obj instanceof SharedUserSetting) {
6466                final SharedUserSetting sus = (SharedUserSetting) obj;
6467                return sus.name + ":" + sus.userId;
6468            } else if (obj instanceof PackageSetting) {
6469                final PackageSetting ps = (PackageSetting) obj;
6470                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6471                    return null;
6472                }
6473                return ps.name;
6474            }
6475            return null;
6476        }
6477    }
6478
6479    @Override
6480    public String[] getNamesForUids(int[] uids) {
6481        if (uids == null || uids.length == 0) {
6482            return null;
6483        }
6484        final int callingUid = Binder.getCallingUid();
6485        if (getInstantAppPackageName(callingUid) != null) {
6486            return null;
6487        }
6488        final String[] names = new String[uids.length];
6489        synchronized (mPackages) {
6490            for (int i = uids.length - 1; i >= 0; i--) {
6491                final int uid = uids[i];
6492                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6493                if (obj instanceof SharedUserSetting) {
6494                    final SharedUserSetting sus = (SharedUserSetting) obj;
6495                    names[i] = "shared:" + sus.name;
6496                } else if (obj instanceof PackageSetting) {
6497                    final PackageSetting ps = (PackageSetting) obj;
6498                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6499                        names[i] = null;
6500                    } else {
6501                        names[i] = ps.name;
6502                    }
6503                } else {
6504                    names[i] = null;
6505                }
6506            }
6507        }
6508        return names;
6509    }
6510
6511    @Override
6512    public int getUidForSharedUser(String sharedUserName) {
6513        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6514            return -1;
6515        }
6516        if (sharedUserName == null) {
6517            return -1;
6518        }
6519        // reader
6520        synchronized (mPackages) {
6521            SharedUserSetting suid;
6522            try {
6523                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6524                if (suid != null) {
6525                    return suid.userId;
6526                }
6527            } catch (PackageManagerException ignore) {
6528                // can't happen, but, still need to catch it
6529            }
6530            return -1;
6531        }
6532    }
6533
6534    @Override
6535    public int getFlagsForUid(int uid) {
6536        final int callingUid = Binder.getCallingUid();
6537        if (getInstantAppPackageName(callingUid) != null) {
6538            return 0;
6539        }
6540        synchronized (mPackages) {
6541            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6542            if (obj instanceof SharedUserSetting) {
6543                final SharedUserSetting sus = (SharedUserSetting) obj;
6544                return sus.pkgFlags;
6545            } else if (obj instanceof PackageSetting) {
6546                final PackageSetting ps = (PackageSetting) obj;
6547                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6548                    return 0;
6549                }
6550                return ps.pkgFlags;
6551            }
6552        }
6553        return 0;
6554    }
6555
6556    @Override
6557    public int getPrivateFlagsForUid(int uid) {
6558        final int callingUid = Binder.getCallingUid();
6559        if (getInstantAppPackageName(callingUid) != null) {
6560            return 0;
6561        }
6562        synchronized (mPackages) {
6563            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6564            if (obj instanceof SharedUserSetting) {
6565                final SharedUserSetting sus = (SharedUserSetting) obj;
6566                return sus.pkgPrivateFlags;
6567            } else if (obj instanceof PackageSetting) {
6568                final PackageSetting ps = (PackageSetting) obj;
6569                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6570                    return 0;
6571                }
6572                return ps.pkgPrivateFlags;
6573            }
6574        }
6575        return 0;
6576    }
6577
6578    @Override
6579    public boolean isUidPrivileged(int uid) {
6580        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6581            return false;
6582        }
6583        uid = UserHandle.getAppId(uid);
6584        // reader
6585        synchronized (mPackages) {
6586            Object obj = mSettings.getUserIdLPr(uid);
6587            if (obj instanceof SharedUserSetting) {
6588                final SharedUserSetting sus = (SharedUserSetting) obj;
6589                final Iterator<PackageSetting> it = sus.packages.iterator();
6590                while (it.hasNext()) {
6591                    if (it.next().isPrivileged()) {
6592                        return true;
6593                    }
6594                }
6595            } else if (obj instanceof PackageSetting) {
6596                final PackageSetting ps = (PackageSetting) obj;
6597                return ps.isPrivileged();
6598            }
6599        }
6600        return false;
6601    }
6602
6603    @Override
6604    public String[] getAppOpPermissionPackages(String permissionName) {
6605        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6606            return null;
6607        }
6608        synchronized (mPackages) {
6609            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6610            if (pkgs == null) {
6611                return null;
6612            }
6613            return pkgs.toArray(new String[pkgs.size()]);
6614        }
6615    }
6616
6617    @Override
6618    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6619            int flags, int userId) {
6620        return resolveIntentInternal(
6621                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6622    }
6623
6624    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6625            int flags, int userId, boolean resolveForStart) {
6626        try {
6627            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6628
6629            if (!sUserManager.exists(userId)) return null;
6630            final int callingUid = Binder.getCallingUid();
6631            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6632            enforceCrossUserPermission(callingUid, userId,
6633                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6634
6635            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6636            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6637                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6638            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6639
6640            final ResolveInfo bestChoice =
6641                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6642            return bestChoice;
6643        } finally {
6644            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6645        }
6646    }
6647
6648    @Override
6649    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6650        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6651            throw new SecurityException(
6652                    "findPersistentPreferredActivity can only be run by the system");
6653        }
6654        if (!sUserManager.exists(userId)) {
6655            return null;
6656        }
6657        final int callingUid = Binder.getCallingUid();
6658        intent = updateIntentForResolve(intent);
6659        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6660        final int flags = updateFlagsForResolve(
6661                0, userId, intent, callingUid, false /*includeInstantApps*/);
6662        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6663                userId);
6664        synchronized (mPackages) {
6665            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6666                    userId);
6667        }
6668    }
6669
6670    @Override
6671    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6672            IntentFilter filter, int match, ComponentName activity) {
6673        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6674            return;
6675        }
6676        final int userId = UserHandle.getCallingUserId();
6677        if (DEBUG_PREFERRED) {
6678            Log.v(TAG, "setLastChosenActivity intent=" + intent
6679                + " resolvedType=" + resolvedType
6680                + " flags=" + flags
6681                + " filter=" + filter
6682                + " match=" + match
6683                + " activity=" + activity);
6684            filter.dump(new PrintStreamPrinter(System.out), "    ");
6685        }
6686        intent.setComponent(null);
6687        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6688                userId);
6689        // Find any earlier preferred or last chosen entries and nuke them
6690        findPreferredActivity(intent, resolvedType,
6691                flags, query, 0, false, true, false, userId);
6692        // Add the new activity as the last chosen for this filter
6693        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6694                "Setting last chosen");
6695    }
6696
6697    @Override
6698    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6699        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6700            return null;
6701        }
6702        final int userId = UserHandle.getCallingUserId();
6703        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6704        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6705                userId);
6706        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6707                false, false, false, userId);
6708    }
6709
6710    /**
6711     * Returns whether or not instant apps have been disabled remotely.
6712     */
6713    private boolean isEphemeralDisabled() {
6714        return mEphemeralAppsDisabled;
6715    }
6716
6717    private boolean isInstantAppAllowed(
6718            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6719            boolean skipPackageCheck) {
6720        if (mInstantAppResolverConnection == null) {
6721            return false;
6722        }
6723        if (mInstantAppInstallerActivity == null) {
6724            return false;
6725        }
6726        if (intent.getComponent() != null) {
6727            return false;
6728        }
6729        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6730            return false;
6731        }
6732        if (!skipPackageCheck && intent.getPackage() != null) {
6733            return false;
6734        }
6735        final boolean isWebUri = hasWebURI(intent);
6736        if (!isWebUri || intent.getData().getHost() == null) {
6737            return false;
6738        }
6739        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6740        // Or if there's already an ephemeral app installed that handles the action
6741        synchronized (mPackages) {
6742            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6743            for (int n = 0; n < count; n++) {
6744                final ResolveInfo info = resolvedActivities.get(n);
6745                final String packageName = info.activityInfo.packageName;
6746                final PackageSetting ps = mSettings.mPackages.get(packageName);
6747                if (ps != null) {
6748                    // only check domain verification status if the app is not a browser
6749                    if (!info.handleAllWebDataURI) {
6750                        // Try to get the status from User settings first
6751                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6752                        final int status = (int) (packedStatus >> 32);
6753                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6754                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6755                            if (DEBUG_EPHEMERAL) {
6756                                Slog.v(TAG, "DENY instant app;"
6757                                    + " pkg: " + packageName + ", status: " + status);
6758                            }
6759                            return false;
6760                        }
6761                    }
6762                    if (ps.getInstantApp(userId)) {
6763                        if (DEBUG_EPHEMERAL) {
6764                            Slog.v(TAG, "DENY instant app installed;"
6765                                    + " pkg: " + packageName);
6766                        }
6767                        return false;
6768                    }
6769                }
6770            }
6771        }
6772        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6773        return true;
6774    }
6775
6776    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6777            Intent origIntent, String resolvedType, String callingPackage,
6778            Bundle verificationBundle, int userId) {
6779        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6780                new InstantAppRequest(responseObj, origIntent, resolvedType,
6781                        callingPackage, userId, verificationBundle));
6782        mHandler.sendMessage(msg);
6783    }
6784
6785    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6786            int flags, List<ResolveInfo> query, int userId) {
6787        if (query != null) {
6788            final int N = query.size();
6789            if (N == 1) {
6790                return query.get(0);
6791            } else if (N > 1) {
6792                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6793                // If there is more than one activity with the same priority,
6794                // then let the user decide between them.
6795                ResolveInfo r0 = query.get(0);
6796                ResolveInfo r1 = query.get(1);
6797                if (DEBUG_INTENT_MATCHING || debug) {
6798                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6799                            + r1.activityInfo.name + "=" + r1.priority);
6800                }
6801                // If the first activity has a higher priority, or a different
6802                // default, then it is always desirable to pick it.
6803                if (r0.priority != r1.priority
6804                        || r0.preferredOrder != r1.preferredOrder
6805                        || r0.isDefault != r1.isDefault) {
6806                    return query.get(0);
6807                }
6808                // If we have saved a preference for a preferred activity for
6809                // this Intent, use that.
6810                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6811                        flags, query, r0.priority, true, false, debug, userId);
6812                if (ri != null) {
6813                    return ri;
6814                }
6815                // If we have an ephemeral app, use it
6816                for (int i = 0; i < N; i++) {
6817                    ri = query.get(i);
6818                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6819                        final String packageName = ri.activityInfo.packageName;
6820                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6821                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6822                        final int status = (int)(packedStatus >> 32);
6823                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6824                            return ri;
6825                        }
6826                    }
6827                }
6828                ri = new ResolveInfo(mResolveInfo);
6829                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6830                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6831                // If all of the options come from the same package, show the application's
6832                // label and icon instead of the generic resolver's.
6833                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6834                // and then throw away the ResolveInfo itself, meaning that the caller loses
6835                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6836                // a fallback for this case; we only set the target package's resources on
6837                // the ResolveInfo, not the ActivityInfo.
6838                final String intentPackage = intent.getPackage();
6839                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6840                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6841                    ri.resolvePackageName = intentPackage;
6842                    if (userNeedsBadging(userId)) {
6843                        ri.noResourceId = true;
6844                    } else {
6845                        ri.icon = appi.icon;
6846                    }
6847                    ri.iconResourceId = appi.icon;
6848                    ri.labelRes = appi.labelRes;
6849                }
6850                ri.activityInfo.applicationInfo = new ApplicationInfo(
6851                        ri.activityInfo.applicationInfo);
6852                if (userId != 0) {
6853                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6854                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6855                }
6856                // Make sure that the resolver is displayable in car mode
6857                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6858                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6859                return ri;
6860            }
6861        }
6862        return null;
6863    }
6864
6865    /**
6866     * Return true if the given list is not empty and all of its contents have
6867     * an activityInfo with the given package name.
6868     */
6869    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6870        if (ArrayUtils.isEmpty(list)) {
6871            return false;
6872        }
6873        for (int i = 0, N = list.size(); i < N; i++) {
6874            final ResolveInfo ri = list.get(i);
6875            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6876            if (ai == null || !packageName.equals(ai.packageName)) {
6877                return false;
6878            }
6879        }
6880        return true;
6881    }
6882
6883    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6884            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6885        final int N = query.size();
6886        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6887                .get(userId);
6888        // Get the list of persistent preferred activities that handle the intent
6889        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6890        List<PersistentPreferredActivity> pprefs = ppir != null
6891                ? ppir.queryIntent(intent, resolvedType,
6892                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6893                        userId)
6894                : null;
6895        if (pprefs != null && pprefs.size() > 0) {
6896            final int M = pprefs.size();
6897            for (int i=0; i<M; i++) {
6898                final PersistentPreferredActivity ppa = pprefs.get(i);
6899                if (DEBUG_PREFERRED || debug) {
6900                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6901                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6902                            + "\n  component=" + ppa.mComponent);
6903                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6904                }
6905                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6906                        flags | MATCH_DISABLED_COMPONENTS, userId);
6907                if (DEBUG_PREFERRED || debug) {
6908                    Slog.v(TAG, "Found persistent preferred activity:");
6909                    if (ai != null) {
6910                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6911                    } else {
6912                        Slog.v(TAG, "  null");
6913                    }
6914                }
6915                if (ai == null) {
6916                    // This previously registered persistent preferred activity
6917                    // component is no longer known. Ignore it and do NOT remove it.
6918                    continue;
6919                }
6920                for (int j=0; j<N; j++) {
6921                    final ResolveInfo ri = query.get(j);
6922                    if (!ri.activityInfo.applicationInfo.packageName
6923                            .equals(ai.applicationInfo.packageName)) {
6924                        continue;
6925                    }
6926                    if (!ri.activityInfo.name.equals(ai.name)) {
6927                        continue;
6928                    }
6929                    //  Found a persistent preference that can handle the intent.
6930                    if (DEBUG_PREFERRED || debug) {
6931                        Slog.v(TAG, "Returning persistent preferred activity: " +
6932                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6933                    }
6934                    return ri;
6935                }
6936            }
6937        }
6938        return null;
6939    }
6940
6941    // TODO: handle preferred activities missing while user has amnesia
6942    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6943            List<ResolveInfo> query, int priority, boolean always,
6944            boolean removeMatches, boolean debug, int userId) {
6945        if (!sUserManager.exists(userId)) return null;
6946        final int callingUid = Binder.getCallingUid();
6947        flags = updateFlagsForResolve(
6948                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6949        intent = updateIntentForResolve(intent);
6950        // writer
6951        synchronized (mPackages) {
6952            // Try to find a matching persistent preferred activity.
6953            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6954                    debug, userId);
6955
6956            // If a persistent preferred activity matched, use it.
6957            if (pri != null) {
6958                return pri;
6959            }
6960
6961            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6962            // Get the list of preferred activities that handle the intent
6963            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6964            List<PreferredActivity> prefs = pir != null
6965                    ? pir.queryIntent(intent, resolvedType,
6966                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6967                            userId)
6968                    : null;
6969            if (prefs != null && prefs.size() > 0) {
6970                boolean changed = false;
6971                try {
6972                    // First figure out how good the original match set is.
6973                    // We will only allow preferred activities that came
6974                    // from the same match quality.
6975                    int match = 0;
6976
6977                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6978
6979                    final int N = query.size();
6980                    for (int j=0; j<N; j++) {
6981                        final ResolveInfo ri = query.get(j);
6982                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6983                                + ": 0x" + Integer.toHexString(match));
6984                        if (ri.match > match) {
6985                            match = ri.match;
6986                        }
6987                    }
6988
6989                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6990                            + Integer.toHexString(match));
6991
6992                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6993                    final int M = prefs.size();
6994                    for (int i=0; i<M; i++) {
6995                        final PreferredActivity pa = prefs.get(i);
6996                        if (DEBUG_PREFERRED || debug) {
6997                            Slog.v(TAG, "Checking PreferredActivity ds="
6998                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6999                                    + "\n  component=" + pa.mPref.mComponent);
7000                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7001                        }
7002                        if (pa.mPref.mMatch != match) {
7003                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
7004                                    + Integer.toHexString(pa.mPref.mMatch));
7005                            continue;
7006                        }
7007                        // If it's not an "always" type preferred activity and that's what we're
7008                        // looking for, skip it.
7009                        if (always && !pa.mPref.mAlways) {
7010                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7011                            continue;
7012                        }
7013                        final ActivityInfo ai = getActivityInfo(
7014                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7015                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7016                                userId);
7017                        if (DEBUG_PREFERRED || debug) {
7018                            Slog.v(TAG, "Found preferred activity:");
7019                            if (ai != null) {
7020                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7021                            } else {
7022                                Slog.v(TAG, "  null");
7023                            }
7024                        }
7025                        if (ai == null) {
7026                            // This previously registered preferred activity
7027                            // component is no longer known.  Most likely an update
7028                            // to the app was installed and in the new version this
7029                            // component no longer exists.  Clean it up by removing
7030                            // it from the preferred activities list, and skip it.
7031                            Slog.w(TAG, "Removing dangling preferred activity: "
7032                                    + pa.mPref.mComponent);
7033                            pir.removeFilter(pa);
7034                            changed = true;
7035                            continue;
7036                        }
7037                        for (int j=0; j<N; j++) {
7038                            final ResolveInfo ri = query.get(j);
7039                            if (!ri.activityInfo.applicationInfo.packageName
7040                                    .equals(ai.applicationInfo.packageName)) {
7041                                continue;
7042                            }
7043                            if (!ri.activityInfo.name.equals(ai.name)) {
7044                                continue;
7045                            }
7046
7047                            if (removeMatches) {
7048                                pir.removeFilter(pa);
7049                                changed = true;
7050                                if (DEBUG_PREFERRED) {
7051                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7052                                }
7053                                break;
7054                            }
7055
7056                            // Okay we found a previously set preferred or last chosen app.
7057                            // If the result set is different from when this
7058                            // was created, and is not a subset of the preferred set, we need to
7059                            // clear it and re-ask the user their preference, if we're looking for
7060                            // an "always" type entry.
7061                            if (always && !pa.mPref.sameSet(query)) {
7062                                if (pa.mPref.isSuperset(query)) {
7063                                    // some components of the set are no longer present in
7064                                    // the query, but the preferred activity can still be reused
7065                                    if (DEBUG_PREFERRED) {
7066                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7067                                                + " still valid as only non-preferred components"
7068                                                + " were removed for " + intent + " type "
7069                                                + resolvedType);
7070                                    }
7071                                    // remove obsolete components and re-add the up-to-date filter
7072                                    PreferredActivity freshPa = new PreferredActivity(pa,
7073                                            pa.mPref.mMatch,
7074                                            pa.mPref.discardObsoleteComponents(query),
7075                                            pa.mPref.mComponent,
7076                                            pa.mPref.mAlways);
7077                                    pir.removeFilter(pa);
7078                                    pir.addFilter(freshPa);
7079                                    changed = true;
7080                                } else {
7081                                    Slog.i(TAG,
7082                                            "Result set changed, dropping preferred activity for "
7083                                                    + intent + " type " + resolvedType);
7084                                    if (DEBUG_PREFERRED) {
7085                                        Slog.v(TAG, "Removing preferred activity since set changed "
7086                                                + pa.mPref.mComponent);
7087                                    }
7088                                    pir.removeFilter(pa);
7089                                    // Re-add the filter as a "last chosen" entry (!always)
7090                                    PreferredActivity lastChosen = new PreferredActivity(
7091                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7092                                    pir.addFilter(lastChosen);
7093                                    changed = true;
7094                                    return null;
7095                                }
7096                            }
7097
7098                            // Yay! Either the set matched or we're looking for the last chosen
7099                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7100                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7101                            return ri;
7102                        }
7103                    }
7104                } finally {
7105                    if (changed) {
7106                        if (DEBUG_PREFERRED) {
7107                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7108                        }
7109                        scheduleWritePackageRestrictionsLocked(userId);
7110                    }
7111                }
7112            }
7113        }
7114        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7115        return null;
7116    }
7117
7118    /*
7119     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7120     */
7121    @Override
7122    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7123            int targetUserId) {
7124        mContext.enforceCallingOrSelfPermission(
7125                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7126        List<CrossProfileIntentFilter> matches =
7127                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7128        if (matches != null) {
7129            int size = matches.size();
7130            for (int i = 0; i < size; i++) {
7131                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7132            }
7133        }
7134        if (hasWebURI(intent)) {
7135            // cross-profile app linking works only towards the parent.
7136            final int callingUid = Binder.getCallingUid();
7137            final UserInfo parent = getProfileParent(sourceUserId);
7138            synchronized(mPackages) {
7139                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7140                        false /*includeInstantApps*/);
7141                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7142                        intent, resolvedType, flags, sourceUserId, parent.id);
7143                return xpDomainInfo != null;
7144            }
7145        }
7146        return false;
7147    }
7148
7149    private UserInfo getProfileParent(int userId) {
7150        final long identity = Binder.clearCallingIdentity();
7151        try {
7152            return sUserManager.getProfileParent(userId);
7153        } finally {
7154            Binder.restoreCallingIdentity(identity);
7155        }
7156    }
7157
7158    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7159            String resolvedType, int userId) {
7160        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7161        if (resolver != null) {
7162            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7163        }
7164        return null;
7165    }
7166
7167    @Override
7168    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7169            String resolvedType, int flags, int userId) {
7170        try {
7171            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7172
7173            return new ParceledListSlice<>(
7174                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7175        } finally {
7176            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7177        }
7178    }
7179
7180    /**
7181     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7182     * instant, returns {@code null}.
7183     */
7184    private String getInstantAppPackageName(int callingUid) {
7185        synchronized (mPackages) {
7186            // If the caller is an isolated app use the owner's uid for the lookup.
7187            if (Process.isIsolated(callingUid)) {
7188                callingUid = mIsolatedOwners.get(callingUid);
7189            }
7190            final int appId = UserHandle.getAppId(callingUid);
7191            final Object obj = mSettings.getUserIdLPr(appId);
7192            if (obj instanceof PackageSetting) {
7193                final PackageSetting ps = (PackageSetting) obj;
7194                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7195                return isInstantApp ? ps.pkg.packageName : null;
7196            }
7197        }
7198        return null;
7199    }
7200
7201    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7202            String resolvedType, int flags, int userId) {
7203        return queryIntentActivitiesInternal(
7204                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7205                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7206    }
7207
7208    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7209            String resolvedType, int flags, int filterCallingUid, int userId,
7210            boolean resolveForStart, boolean allowDynamicSplits) {
7211        if (!sUserManager.exists(userId)) return Collections.emptyList();
7212        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7213        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7214                false /* requireFullPermission */, false /* checkShell */,
7215                "query intent activities");
7216        final String pkgName = intent.getPackage();
7217        ComponentName comp = intent.getComponent();
7218        if (comp == null) {
7219            if (intent.getSelector() != null) {
7220                intent = intent.getSelector();
7221                comp = intent.getComponent();
7222            }
7223        }
7224
7225        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7226                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7227        if (comp != null) {
7228            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7229            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7230            if (ai != null) {
7231                // When specifying an explicit component, we prevent the activity from being
7232                // used when either 1) the calling package is normal and the activity is within
7233                // an ephemeral application or 2) the calling package is ephemeral and the
7234                // activity is not visible to ephemeral applications.
7235                final boolean matchInstantApp =
7236                        (flags & PackageManager.MATCH_INSTANT) != 0;
7237                final boolean matchVisibleToInstantAppOnly =
7238                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7239                final boolean matchExplicitlyVisibleOnly =
7240                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7241                final boolean isCallerInstantApp =
7242                        instantAppPkgName != null;
7243                final boolean isTargetSameInstantApp =
7244                        comp.getPackageName().equals(instantAppPkgName);
7245                final boolean isTargetInstantApp =
7246                        (ai.applicationInfo.privateFlags
7247                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7248                final boolean isTargetVisibleToInstantApp =
7249                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7250                final boolean isTargetExplicitlyVisibleToInstantApp =
7251                        isTargetVisibleToInstantApp
7252                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7253                final boolean isTargetHiddenFromInstantApp =
7254                        !isTargetVisibleToInstantApp
7255                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7256                final boolean blockResolution =
7257                        !isTargetSameInstantApp
7258                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7259                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7260                                        && isTargetHiddenFromInstantApp));
7261                if (!blockResolution) {
7262                    final ResolveInfo ri = new ResolveInfo();
7263                    ri.activityInfo = ai;
7264                    list.add(ri);
7265                }
7266            }
7267            return applyPostResolutionFilter(
7268                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7269        }
7270
7271        // reader
7272        boolean sortResult = false;
7273        boolean addEphemeral = false;
7274        List<ResolveInfo> result;
7275        final boolean ephemeralDisabled = isEphemeralDisabled();
7276        synchronized (mPackages) {
7277            if (pkgName == null) {
7278                List<CrossProfileIntentFilter> matchingFilters =
7279                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7280                // Check for results that need to skip the current profile.
7281                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7282                        resolvedType, flags, userId);
7283                if (xpResolveInfo != null) {
7284                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7285                    xpResult.add(xpResolveInfo);
7286                    return applyPostResolutionFilter(
7287                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7288                            allowDynamicSplits, filterCallingUid, userId);
7289                }
7290
7291                // Check for results in the current profile.
7292                result = filterIfNotSystemUser(mActivities.queryIntent(
7293                        intent, resolvedType, flags, userId), userId);
7294                addEphemeral = !ephemeralDisabled
7295                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7296                // Check for cross profile results.
7297                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7298                xpResolveInfo = queryCrossProfileIntents(
7299                        matchingFilters, intent, resolvedType, flags, userId,
7300                        hasNonNegativePriorityResult);
7301                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7302                    boolean isVisibleToUser = filterIfNotSystemUser(
7303                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7304                    if (isVisibleToUser) {
7305                        result.add(xpResolveInfo);
7306                        sortResult = true;
7307                    }
7308                }
7309                if (hasWebURI(intent)) {
7310                    CrossProfileDomainInfo xpDomainInfo = null;
7311                    final UserInfo parent = getProfileParent(userId);
7312                    if (parent != null) {
7313                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7314                                flags, userId, parent.id);
7315                    }
7316                    if (xpDomainInfo != null) {
7317                        if (xpResolveInfo != null) {
7318                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7319                            // in the result.
7320                            result.remove(xpResolveInfo);
7321                        }
7322                        if (result.size() == 0 && !addEphemeral) {
7323                            // No result in current profile, but found candidate in parent user.
7324                            // And we are not going to add emphemeral app, so we can return the
7325                            // result straight away.
7326                            result.add(xpDomainInfo.resolveInfo);
7327                            return applyPostResolutionFilter(result, instantAppPkgName,
7328                                    allowDynamicSplits, filterCallingUid, userId);
7329                        }
7330                    } else if (result.size() <= 1 && !addEphemeral) {
7331                        // No result in parent user and <= 1 result in current profile, and we
7332                        // are not going to add emphemeral app, so we can return the result without
7333                        // further processing.
7334                        return applyPostResolutionFilter(result, instantAppPkgName,
7335                                allowDynamicSplits, filterCallingUid, userId);
7336                    }
7337                    // We have more than one candidate (combining results from current and parent
7338                    // profile), so we need filtering and sorting.
7339                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7340                            intent, flags, result, xpDomainInfo, userId);
7341                    sortResult = true;
7342                }
7343            } else {
7344                final PackageParser.Package pkg = mPackages.get(pkgName);
7345                result = null;
7346                if (pkg != null) {
7347                    result = filterIfNotSystemUser(
7348                            mActivities.queryIntentForPackage(
7349                                    intent, resolvedType, flags, pkg.activities, userId),
7350                            userId);
7351                }
7352                if (result == null || result.size() == 0) {
7353                    // the caller wants to resolve for a particular package; however, there
7354                    // were no installed results, so, try to find an ephemeral result
7355                    addEphemeral = !ephemeralDisabled
7356                            && isInstantAppAllowed(
7357                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7358                    if (result == null) {
7359                        result = new ArrayList<>();
7360                    }
7361                }
7362            }
7363        }
7364        if (addEphemeral) {
7365            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7366        }
7367        if (sortResult) {
7368            Collections.sort(result, mResolvePrioritySorter);
7369        }
7370        return applyPostResolutionFilter(
7371                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7372    }
7373
7374    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7375            String resolvedType, int flags, int userId) {
7376        // first, check to see if we've got an instant app already installed
7377        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7378        ResolveInfo localInstantApp = null;
7379        boolean blockResolution = false;
7380        if (!alreadyResolvedLocally) {
7381            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7382                    flags
7383                        | PackageManager.GET_RESOLVED_FILTER
7384                        | PackageManager.MATCH_INSTANT
7385                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7386                    userId);
7387            for (int i = instantApps.size() - 1; i >= 0; --i) {
7388                final ResolveInfo info = instantApps.get(i);
7389                final String packageName = info.activityInfo.packageName;
7390                final PackageSetting ps = mSettings.mPackages.get(packageName);
7391                if (ps.getInstantApp(userId)) {
7392                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7393                    final int status = (int)(packedStatus >> 32);
7394                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7395                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7396                        // there's a local instant application installed, but, the user has
7397                        // chosen to never use it; skip resolution and don't acknowledge
7398                        // an instant application is even available
7399                        if (DEBUG_EPHEMERAL) {
7400                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7401                        }
7402                        blockResolution = true;
7403                        break;
7404                    } else {
7405                        // we have a locally installed instant application; skip resolution
7406                        // but acknowledge there's an instant application available
7407                        if (DEBUG_EPHEMERAL) {
7408                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7409                        }
7410                        localInstantApp = info;
7411                        break;
7412                    }
7413                }
7414            }
7415        }
7416        // no app installed, let's see if one's available
7417        AuxiliaryResolveInfo auxiliaryResponse = null;
7418        if (!blockResolution) {
7419            if (localInstantApp == null) {
7420                // we don't have an instant app locally, resolve externally
7421                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7422                final InstantAppRequest requestObject = new InstantAppRequest(
7423                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7424                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7425                auxiliaryResponse =
7426                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7427                                mContext, mInstantAppResolverConnection, requestObject);
7428                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7429            } else {
7430                // we have an instant application locally, but, we can't admit that since
7431                // callers shouldn't be able to determine prior browsing. create a dummy
7432                // auxiliary response so the downstream code behaves as if there's an
7433                // instant application available externally. when it comes time to start
7434                // the instant application, we'll do the right thing.
7435                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7436                auxiliaryResponse = new AuxiliaryResolveInfo(
7437                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7438                        ai.versionCode, null /*failureIntent*/);
7439            }
7440        }
7441        if (auxiliaryResponse != null) {
7442            if (DEBUG_EPHEMERAL) {
7443                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7444            }
7445            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7446            final PackageSetting ps =
7447                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7448            if (ps != null) {
7449                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7450                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7451                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7452                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7453                // make sure this resolver is the default
7454                ephemeralInstaller.isDefault = true;
7455                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7456                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7457                // add a non-generic filter
7458                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7459                ephemeralInstaller.filter.addDataPath(
7460                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7461                ephemeralInstaller.isInstantAppAvailable = true;
7462                result.add(ephemeralInstaller);
7463            }
7464        }
7465        return result;
7466    }
7467
7468    private static class CrossProfileDomainInfo {
7469        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7470        ResolveInfo resolveInfo;
7471        /* Best domain verification status of the activities found in the other profile */
7472        int bestDomainVerificationStatus;
7473    }
7474
7475    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7476            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7477        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7478                sourceUserId)) {
7479            return null;
7480        }
7481        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7482                resolvedType, flags, parentUserId);
7483
7484        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7485            return null;
7486        }
7487        CrossProfileDomainInfo result = null;
7488        int size = resultTargetUser.size();
7489        for (int i = 0; i < size; i++) {
7490            ResolveInfo riTargetUser = resultTargetUser.get(i);
7491            // Intent filter verification is only for filters that specify a host. So don't return
7492            // those that handle all web uris.
7493            if (riTargetUser.handleAllWebDataURI) {
7494                continue;
7495            }
7496            String packageName = riTargetUser.activityInfo.packageName;
7497            PackageSetting ps = mSettings.mPackages.get(packageName);
7498            if (ps == null) {
7499                continue;
7500            }
7501            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7502            int status = (int)(verificationState >> 32);
7503            if (result == null) {
7504                result = new CrossProfileDomainInfo();
7505                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7506                        sourceUserId, parentUserId);
7507                result.bestDomainVerificationStatus = status;
7508            } else {
7509                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7510                        result.bestDomainVerificationStatus);
7511            }
7512        }
7513        // Don't consider matches with status NEVER across profiles.
7514        if (result != null && result.bestDomainVerificationStatus
7515                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7516            return null;
7517        }
7518        return result;
7519    }
7520
7521    /**
7522     * Verification statuses are ordered from the worse to the best, except for
7523     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7524     */
7525    private int bestDomainVerificationStatus(int status1, int status2) {
7526        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7527            return status2;
7528        }
7529        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7530            return status1;
7531        }
7532        return (int) MathUtils.max(status1, status2);
7533    }
7534
7535    private boolean isUserEnabled(int userId) {
7536        long callingId = Binder.clearCallingIdentity();
7537        try {
7538            UserInfo userInfo = sUserManager.getUserInfo(userId);
7539            return userInfo != null && userInfo.isEnabled();
7540        } finally {
7541            Binder.restoreCallingIdentity(callingId);
7542        }
7543    }
7544
7545    /**
7546     * Filter out activities with systemUserOnly flag set, when current user is not System.
7547     *
7548     * @return filtered list
7549     */
7550    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7551        if (userId == UserHandle.USER_SYSTEM) {
7552            return resolveInfos;
7553        }
7554        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7555            ResolveInfo info = resolveInfos.get(i);
7556            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7557                resolveInfos.remove(i);
7558            }
7559        }
7560        return resolveInfos;
7561    }
7562
7563    /**
7564     * Filters out ephemeral activities.
7565     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7566     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7567     *
7568     * @param resolveInfos The pre-filtered list of resolved activities
7569     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7570     *          is performed.
7571     * @return A filtered list of resolved activities.
7572     */
7573    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7574            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7575        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7576            final ResolveInfo info = resolveInfos.get(i);
7577            // allow activities that are defined in the provided package
7578            if (allowDynamicSplits
7579                    && info.activityInfo.splitName != null
7580                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7581                            info.activityInfo.splitName)) {
7582                // requested activity is defined in a split that hasn't been installed yet.
7583                // add the installer to the resolve list
7584                if (DEBUG_INSTALL) {
7585                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7586                }
7587                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7588                final ComponentName installFailureActivity = findInstallFailureActivity(
7589                        info.activityInfo.packageName,  filterCallingUid, userId);
7590                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7591                        info.activityInfo.packageName, info.activityInfo.splitName,
7592                        installFailureActivity,
7593                        info.activityInfo.applicationInfo.versionCode,
7594                        null /*failureIntent*/);
7595                // make sure this resolver is the default
7596                installerInfo.isDefault = true;
7597                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7598                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7599                // add a non-generic filter
7600                installerInfo.filter = new IntentFilter();
7601                // load resources from the correct package
7602                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7603                resolveInfos.set(i, installerInfo);
7604                continue;
7605            }
7606            // caller is a full app, don't need to apply any other filtering
7607            if (ephemeralPkgName == null) {
7608                continue;
7609            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7610                // caller is same app; don't need to apply any other filtering
7611                continue;
7612            }
7613            // allow activities that have been explicitly exposed to ephemeral apps
7614            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7615            if (!isEphemeralApp
7616                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7617                continue;
7618            }
7619            resolveInfos.remove(i);
7620        }
7621        return resolveInfos;
7622    }
7623
7624    /**
7625     * Returns the activity component that can handle install failures.
7626     * <p>By default, the instant application installer handles failures. However, an
7627     * application may want to handle failures on its own. Applications do this by
7628     * creating an activity with an intent filter that handles the action
7629     * {@link Intent#ACTION_INSTALL_FAILURE}.
7630     */
7631    private @Nullable ComponentName findInstallFailureActivity(
7632            String packageName, int filterCallingUid, int userId) {
7633        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7634        failureActivityIntent.setPackage(packageName);
7635        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7636        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7637                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7638                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7639        final int NR = result.size();
7640        if (NR > 0) {
7641            for (int i = 0; i < NR; i++) {
7642                final ResolveInfo info = result.get(i);
7643                if (info.activityInfo.splitName != null) {
7644                    continue;
7645                }
7646                return new ComponentName(packageName, info.activityInfo.name);
7647            }
7648        }
7649        return null;
7650    }
7651
7652    /**
7653     * @param resolveInfos list of resolve infos in descending priority order
7654     * @return if the list contains a resolve info with non-negative priority
7655     */
7656    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7657        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7658    }
7659
7660    private static boolean hasWebURI(Intent intent) {
7661        if (intent.getData() == null) {
7662            return false;
7663        }
7664        final String scheme = intent.getScheme();
7665        if (TextUtils.isEmpty(scheme)) {
7666            return false;
7667        }
7668        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7669    }
7670
7671    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7672            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7673            int userId) {
7674        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7675
7676        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7677            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7678                    candidates.size());
7679        }
7680
7681        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7682        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7683        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7684        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7685        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7686        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7687
7688        synchronized (mPackages) {
7689            final int count = candidates.size();
7690            // First, try to use linked apps. Partition the candidates into four lists:
7691            // one for the final results, one for the "do not use ever", one for "undefined status"
7692            // and finally one for "browser app type".
7693            for (int n=0; n<count; n++) {
7694                ResolveInfo info = candidates.get(n);
7695                String packageName = info.activityInfo.packageName;
7696                PackageSetting ps = mSettings.mPackages.get(packageName);
7697                if (ps != null) {
7698                    // Add to the special match all list (Browser use case)
7699                    if (info.handleAllWebDataURI) {
7700                        matchAllList.add(info);
7701                        continue;
7702                    }
7703                    // Try to get the status from User settings first
7704                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7705                    int status = (int)(packedStatus >> 32);
7706                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7707                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7708                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7709                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7710                                    + " : linkgen=" + linkGeneration);
7711                        }
7712                        // Use link-enabled generation as preferredOrder, i.e.
7713                        // prefer newly-enabled over earlier-enabled.
7714                        info.preferredOrder = linkGeneration;
7715                        alwaysList.add(info);
7716                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7717                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7718                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7719                        }
7720                        neverList.add(info);
7721                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7722                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7723                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7724                        }
7725                        alwaysAskList.add(info);
7726                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7727                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7728                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7729                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7730                        }
7731                        undefinedList.add(info);
7732                    }
7733                }
7734            }
7735
7736            // We'll want to include browser possibilities in a few cases
7737            boolean includeBrowser = false;
7738
7739            // First try to add the "always" resolution(s) for the current user, if any
7740            if (alwaysList.size() > 0) {
7741                result.addAll(alwaysList);
7742            } else {
7743                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7744                result.addAll(undefinedList);
7745                // Maybe add one for the other profile.
7746                if (xpDomainInfo != null && (
7747                        xpDomainInfo.bestDomainVerificationStatus
7748                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7749                    result.add(xpDomainInfo.resolveInfo);
7750                }
7751                includeBrowser = true;
7752            }
7753
7754            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7755            // If there were 'always' entries their preferred order has been set, so we also
7756            // back that off to make the alternatives equivalent
7757            if (alwaysAskList.size() > 0) {
7758                for (ResolveInfo i : result) {
7759                    i.preferredOrder = 0;
7760                }
7761                result.addAll(alwaysAskList);
7762                includeBrowser = true;
7763            }
7764
7765            if (includeBrowser) {
7766                // Also add browsers (all of them or only the default one)
7767                if (DEBUG_DOMAIN_VERIFICATION) {
7768                    Slog.v(TAG, "   ...including browsers in candidate set");
7769                }
7770                if ((matchFlags & MATCH_ALL) != 0) {
7771                    result.addAll(matchAllList);
7772                } else {
7773                    // Browser/generic handling case.  If there's a default browser, go straight
7774                    // to that (but only if there is no other higher-priority match).
7775                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7776                    int maxMatchPrio = 0;
7777                    ResolveInfo defaultBrowserMatch = null;
7778                    final int numCandidates = matchAllList.size();
7779                    for (int n = 0; n < numCandidates; n++) {
7780                        ResolveInfo info = matchAllList.get(n);
7781                        // track the highest overall match priority...
7782                        if (info.priority > maxMatchPrio) {
7783                            maxMatchPrio = info.priority;
7784                        }
7785                        // ...and the highest-priority default browser match
7786                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7787                            if (defaultBrowserMatch == null
7788                                    || (defaultBrowserMatch.priority < info.priority)) {
7789                                if (debug) {
7790                                    Slog.v(TAG, "Considering default browser match " + info);
7791                                }
7792                                defaultBrowserMatch = info;
7793                            }
7794                        }
7795                    }
7796                    if (defaultBrowserMatch != null
7797                            && defaultBrowserMatch.priority >= maxMatchPrio
7798                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7799                    {
7800                        if (debug) {
7801                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7802                        }
7803                        result.add(defaultBrowserMatch);
7804                    } else {
7805                        result.addAll(matchAllList);
7806                    }
7807                }
7808
7809                // If there is nothing selected, add all candidates and remove the ones that the user
7810                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7811                if (result.size() == 0) {
7812                    result.addAll(candidates);
7813                    result.removeAll(neverList);
7814                }
7815            }
7816        }
7817        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7818            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7819                    result.size());
7820            for (ResolveInfo info : result) {
7821                Slog.v(TAG, "  + " + info.activityInfo);
7822            }
7823        }
7824        return result;
7825    }
7826
7827    // Returns a packed value as a long:
7828    //
7829    // high 'int'-sized word: link status: undefined/ask/never/always.
7830    // low 'int'-sized word: relative priority among 'always' results.
7831    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7832        long result = ps.getDomainVerificationStatusForUser(userId);
7833        // if none available, get the master status
7834        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7835            if (ps.getIntentFilterVerificationInfo() != null) {
7836                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7837            }
7838        }
7839        return result;
7840    }
7841
7842    private ResolveInfo querySkipCurrentProfileIntents(
7843            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7844            int flags, int sourceUserId) {
7845        if (matchingFilters != null) {
7846            int size = matchingFilters.size();
7847            for (int i = 0; i < size; i ++) {
7848                CrossProfileIntentFilter filter = matchingFilters.get(i);
7849                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7850                    // Checking if there are activities in the target user that can handle the
7851                    // intent.
7852                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7853                            resolvedType, flags, sourceUserId);
7854                    if (resolveInfo != null) {
7855                        return resolveInfo;
7856                    }
7857                }
7858            }
7859        }
7860        return null;
7861    }
7862
7863    // Return matching ResolveInfo in target user if any.
7864    private ResolveInfo queryCrossProfileIntents(
7865            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7866            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7867        if (matchingFilters != null) {
7868            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7869            // match the same intent. For performance reasons, it is better not to
7870            // run queryIntent twice for the same userId
7871            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7872            int size = matchingFilters.size();
7873            for (int i = 0; i < size; i++) {
7874                CrossProfileIntentFilter filter = matchingFilters.get(i);
7875                int targetUserId = filter.getTargetUserId();
7876                boolean skipCurrentProfile =
7877                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7878                boolean skipCurrentProfileIfNoMatchFound =
7879                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7880                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7881                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7882                    // Checking if there are activities in the target user that can handle the
7883                    // intent.
7884                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7885                            resolvedType, flags, sourceUserId);
7886                    if (resolveInfo != null) return resolveInfo;
7887                    alreadyTriedUserIds.put(targetUserId, true);
7888                }
7889            }
7890        }
7891        return null;
7892    }
7893
7894    /**
7895     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7896     * will forward the intent to the filter's target user.
7897     * Otherwise, returns null.
7898     */
7899    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7900            String resolvedType, int flags, int sourceUserId) {
7901        int targetUserId = filter.getTargetUserId();
7902        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7903                resolvedType, flags, targetUserId);
7904        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7905            // If all the matches in the target profile are suspended, return null.
7906            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7907                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7908                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7909                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7910                            targetUserId);
7911                }
7912            }
7913        }
7914        return null;
7915    }
7916
7917    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7918            int sourceUserId, int targetUserId) {
7919        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7920        long ident = Binder.clearCallingIdentity();
7921        boolean targetIsProfile;
7922        try {
7923            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7924        } finally {
7925            Binder.restoreCallingIdentity(ident);
7926        }
7927        String className;
7928        if (targetIsProfile) {
7929            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7930        } else {
7931            className = FORWARD_INTENT_TO_PARENT;
7932        }
7933        ComponentName forwardingActivityComponentName = new ComponentName(
7934                mAndroidApplication.packageName, className);
7935        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7936                sourceUserId);
7937        if (!targetIsProfile) {
7938            forwardingActivityInfo.showUserIcon = targetUserId;
7939            forwardingResolveInfo.noResourceId = true;
7940        }
7941        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7942        forwardingResolveInfo.priority = 0;
7943        forwardingResolveInfo.preferredOrder = 0;
7944        forwardingResolveInfo.match = 0;
7945        forwardingResolveInfo.isDefault = true;
7946        forwardingResolveInfo.filter = filter;
7947        forwardingResolveInfo.targetUserId = targetUserId;
7948        return forwardingResolveInfo;
7949    }
7950
7951    @Override
7952    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7953            Intent[] specifics, String[] specificTypes, Intent intent,
7954            String resolvedType, int flags, int userId) {
7955        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7956                specificTypes, intent, resolvedType, flags, userId));
7957    }
7958
7959    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7960            Intent[] specifics, String[] specificTypes, Intent intent,
7961            String resolvedType, int flags, int userId) {
7962        if (!sUserManager.exists(userId)) return Collections.emptyList();
7963        final int callingUid = Binder.getCallingUid();
7964        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7965                false /*includeInstantApps*/);
7966        enforceCrossUserPermission(callingUid, userId,
7967                false /*requireFullPermission*/, false /*checkShell*/,
7968                "query intent activity options");
7969        final String resultsAction = intent.getAction();
7970
7971        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7972                | PackageManager.GET_RESOLVED_FILTER, userId);
7973
7974        if (DEBUG_INTENT_MATCHING) {
7975            Log.v(TAG, "Query " + intent + ": " + results);
7976        }
7977
7978        int specificsPos = 0;
7979        int N;
7980
7981        // todo: note that the algorithm used here is O(N^2).  This
7982        // isn't a problem in our current environment, but if we start running
7983        // into situations where we have more than 5 or 10 matches then this
7984        // should probably be changed to something smarter...
7985
7986        // First we go through and resolve each of the specific items
7987        // that were supplied, taking care of removing any corresponding
7988        // duplicate items in the generic resolve list.
7989        if (specifics != null) {
7990            for (int i=0; i<specifics.length; i++) {
7991                final Intent sintent = specifics[i];
7992                if (sintent == null) {
7993                    continue;
7994                }
7995
7996                if (DEBUG_INTENT_MATCHING) {
7997                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7998                }
7999
8000                String action = sintent.getAction();
8001                if (resultsAction != null && resultsAction.equals(action)) {
8002                    // If this action was explicitly requested, then don't
8003                    // remove things that have it.
8004                    action = null;
8005                }
8006
8007                ResolveInfo ri = null;
8008                ActivityInfo ai = null;
8009
8010                ComponentName comp = sintent.getComponent();
8011                if (comp == null) {
8012                    ri = resolveIntent(
8013                        sintent,
8014                        specificTypes != null ? specificTypes[i] : null,
8015                            flags, userId);
8016                    if (ri == null) {
8017                        continue;
8018                    }
8019                    if (ri == mResolveInfo) {
8020                        // ACK!  Must do something better with this.
8021                    }
8022                    ai = ri.activityInfo;
8023                    comp = new ComponentName(ai.applicationInfo.packageName,
8024                            ai.name);
8025                } else {
8026                    ai = getActivityInfo(comp, flags, userId);
8027                    if (ai == null) {
8028                        continue;
8029                    }
8030                }
8031
8032                // Look for any generic query activities that are duplicates
8033                // of this specific one, and remove them from the results.
8034                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8035                N = results.size();
8036                int j;
8037                for (j=specificsPos; j<N; j++) {
8038                    ResolveInfo sri = results.get(j);
8039                    if ((sri.activityInfo.name.equals(comp.getClassName())
8040                            && sri.activityInfo.applicationInfo.packageName.equals(
8041                                    comp.getPackageName()))
8042                        || (action != null && sri.filter.matchAction(action))) {
8043                        results.remove(j);
8044                        if (DEBUG_INTENT_MATCHING) Log.v(
8045                            TAG, "Removing duplicate item from " + j
8046                            + " due to specific " + specificsPos);
8047                        if (ri == null) {
8048                            ri = sri;
8049                        }
8050                        j--;
8051                        N--;
8052                    }
8053                }
8054
8055                // Add this specific item to its proper place.
8056                if (ri == null) {
8057                    ri = new ResolveInfo();
8058                    ri.activityInfo = ai;
8059                }
8060                results.add(specificsPos, ri);
8061                ri.specificIndex = i;
8062                specificsPos++;
8063            }
8064        }
8065
8066        // Now we go through the remaining generic results and remove any
8067        // duplicate actions that are found here.
8068        N = results.size();
8069        for (int i=specificsPos; i<N-1; i++) {
8070            final ResolveInfo rii = results.get(i);
8071            if (rii.filter == null) {
8072                continue;
8073            }
8074
8075            // Iterate over all of the actions of this result's intent
8076            // filter...  typically this should be just one.
8077            final Iterator<String> it = rii.filter.actionsIterator();
8078            if (it == null) {
8079                continue;
8080            }
8081            while (it.hasNext()) {
8082                final String action = it.next();
8083                if (resultsAction != null && resultsAction.equals(action)) {
8084                    // If this action was explicitly requested, then don't
8085                    // remove things that have it.
8086                    continue;
8087                }
8088                for (int j=i+1; j<N; j++) {
8089                    final ResolveInfo rij = results.get(j);
8090                    if (rij.filter != null && rij.filter.hasAction(action)) {
8091                        results.remove(j);
8092                        if (DEBUG_INTENT_MATCHING) Log.v(
8093                            TAG, "Removing duplicate item from " + j
8094                            + " due to action " + action + " at " + i);
8095                        j--;
8096                        N--;
8097                    }
8098                }
8099            }
8100
8101            // If the caller didn't request filter information, drop it now
8102            // so we don't have to marshall/unmarshall it.
8103            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8104                rii.filter = null;
8105            }
8106        }
8107
8108        // Filter out the caller activity if so requested.
8109        if (caller != null) {
8110            N = results.size();
8111            for (int i=0; i<N; i++) {
8112                ActivityInfo ainfo = results.get(i).activityInfo;
8113                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8114                        && caller.getClassName().equals(ainfo.name)) {
8115                    results.remove(i);
8116                    break;
8117                }
8118            }
8119        }
8120
8121        // If the caller didn't request filter information,
8122        // drop them now so we don't have to
8123        // marshall/unmarshall it.
8124        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8125            N = results.size();
8126            for (int i=0; i<N; i++) {
8127                results.get(i).filter = null;
8128            }
8129        }
8130
8131        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8132        return results;
8133    }
8134
8135    @Override
8136    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8137            String resolvedType, int flags, int userId) {
8138        return new ParceledListSlice<>(
8139                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8140                        false /*allowDynamicSplits*/));
8141    }
8142
8143    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8144            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8145        if (!sUserManager.exists(userId)) return Collections.emptyList();
8146        final int callingUid = Binder.getCallingUid();
8147        enforceCrossUserPermission(callingUid, userId,
8148                false /*requireFullPermission*/, false /*checkShell*/,
8149                "query intent receivers");
8150        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8151        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8152                false /*includeInstantApps*/);
8153        ComponentName comp = intent.getComponent();
8154        if (comp == null) {
8155            if (intent.getSelector() != null) {
8156                intent = intent.getSelector();
8157                comp = intent.getComponent();
8158            }
8159        }
8160        if (comp != null) {
8161            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8162            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8163            if (ai != null) {
8164                // When specifying an explicit component, we prevent the activity from being
8165                // used when either 1) the calling package is normal and the activity is within
8166                // an instant application or 2) the calling package is ephemeral and the
8167                // activity is not visible to instant applications.
8168                final boolean matchInstantApp =
8169                        (flags & PackageManager.MATCH_INSTANT) != 0;
8170                final boolean matchVisibleToInstantAppOnly =
8171                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8172                final boolean matchExplicitlyVisibleOnly =
8173                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8174                final boolean isCallerInstantApp =
8175                        instantAppPkgName != null;
8176                final boolean isTargetSameInstantApp =
8177                        comp.getPackageName().equals(instantAppPkgName);
8178                final boolean isTargetInstantApp =
8179                        (ai.applicationInfo.privateFlags
8180                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8181                final boolean isTargetVisibleToInstantApp =
8182                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8183                final boolean isTargetExplicitlyVisibleToInstantApp =
8184                        isTargetVisibleToInstantApp
8185                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8186                final boolean isTargetHiddenFromInstantApp =
8187                        !isTargetVisibleToInstantApp
8188                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8189                final boolean blockResolution =
8190                        !isTargetSameInstantApp
8191                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8192                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8193                                        && isTargetHiddenFromInstantApp));
8194                if (!blockResolution) {
8195                    ResolveInfo ri = new ResolveInfo();
8196                    ri.activityInfo = ai;
8197                    list.add(ri);
8198                }
8199            }
8200            return applyPostResolutionFilter(
8201                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8202        }
8203
8204        // reader
8205        synchronized (mPackages) {
8206            String pkgName = intent.getPackage();
8207            if (pkgName == null) {
8208                final List<ResolveInfo> result =
8209                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8210                return applyPostResolutionFilter(
8211                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8212            }
8213            final PackageParser.Package pkg = mPackages.get(pkgName);
8214            if (pkg != null) {
8215                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8216                        intent, resolvedType, flags, pkg.receivers, userId);
8217                return applyPostResolutionFilter(
8218                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8219            }
8220            return Collections.emptyList();
8221        }
8222    }
8223
8224    @Override
8225    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8226        final int callingUid = Binder.getCallingUid();
8227        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8228    }
8229
8230    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8231            int userId, int callingUid) {
8232        if (!sUserManager.exists(userId)) return null;
8233        flags = updateFlagsForResolve(
8234                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8235        List<ResolveInfo> query = queryIntentServicesInternal(
8236                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8237        if (query != null) {
8238            if (query.size() >= 1) {
8239                // If there is more than one service with the same priority,
8240                // just arbitrarily pick the first one.
8241                return query.get(0);
8242            }
8243        }
8244        return null;
8245    }
8246
8247    @Override
8248    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8249            String resolvedType, int flags, int userId) {
8250        final int callingUid = Binder.getCallingUid();
8251        return new ParceledListSlice<>(queryIntentServicesInternal(
8252                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8253    }
8254
8255    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8256            String resolvedType, int flags, int userId, int callingUid,
8257            boolean includeInstantApps) {
8258        if (!sUserManager.exists(userId)) return Collections.emptyList();
8259        enforceCrossUserPermission(callingUid, userId,
8260                false /*requireFullPermission*/, false /*checkShell*/,
8261                "query intent receivers");
8262        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8263        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8264        ComponentName comp = intent.getComponent();
8265        if (comp == null) {
8266            if (intent.getSelector() != null) {
8267                intent = intent.getSelector();
8268                comp = intent.getComponent();
8269            }
8270        }
8271        if (comp != null) {
8272            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8273            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8274            if (si != null) {
8275                // When specifying an explicit component, we prevent the service from being
8276                // used when either 1) the service is in an instant application and the
8277                // caller is not the same instant application or 2) the calling package is
8278                // ephemeral and the activity is not visible to ephemeral applications.
8279                final boolean matchInstantApp =
8280                        (flags & PackageManager.MATCH_INSTANT) != 0;
8281                final boolean matchVisibleToInstantAppOnly =
8282                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8283                final boolean isCallerInstantApp =
8284                        instantAppPkgName != null;
8285                final boolean isTargetSameInstantApp =
8286                        comp.getPackageName().equals(instantAppPkgName);
8287                final boolean isTargetInstantApp =
8288                        (si.applicationInfo.privateFlags
8289                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8290                final boolean isTargetHiddenFromInstantApp =
8291                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8292                final boolean blockResolution =
8293                        !isTargetSameInstantApp
8294                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8295                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8296                                        && isTargetHiddenFromInstantApp));
8297                if (!blockResolution) {
8298                    final ResolveInfo ri = new ResolveInfo();
8299                    ri.serviceInfo = si;
8300                    list.add(ri);
8301                }
8302            }
8303            return list;
8304        }
8305
8306        // reader
8307        synchronized (mPackages) {
8308            String pkgName = intent.getPackage();
8309            if (pkgName == null) {
8310                return applyPostServiceResolutionFilter(
8311                        mServices.queryIntent(intent, resolvedType, flags, userId),
8312                        instantAppPkgName);
8313            }
8314            final PackageParser.Package pkg = mPackages.get(pkgName);
8315            if (pkg != null) {
8316                return applyPostServiceResolutionFilter(
8317                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8318                                userId),
8319                        instantAppPkgName);
8320            }
8321            return Collections.emptyList();
8322        }
8323    }
8324
8325    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8326            String instantAppPkgName) {
8327        if (instantAppPkgName == null) {
8328            return resolveInfos;
8329        }
8330        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8331            final ResolveInfo info = resolveInfos.get(i);
8332            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8333            // allow services that are defined in the provided package
8334            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8335                if (info.serviceInfo.splitName != null
8336                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8337                                info.serviceInfo.splitName)) {
8338                    // requested service is defined in a split that hasn't been installed yet.
8339                    // add the installer to the resolve list
8340                    if (DEBUG_EPHEMERAL) {
8341                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8342                    }
8343                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8344                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8345                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8346                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8347                            null /*failureIntent*/);
8348                    // make sure this resolver is the default
8349                    installerInfo.isDefault = true;
8350                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8351                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8352                    // add a non-generic filter
8353                    installerInfo.filter = new IntentFilter();
8354                    // load resources from the correct package
8355                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8356                    resolveInfos.set(i, installerInfo);
8357                }
8358                continue;
8359            }
8360            // allow services that have been explicitly exposed to ephemeral apps
8361            if (!isEphemeralApp
8362                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8363                continue;
8364            }
8365            resolveInfos.remove(i);
8366        }
8367        return resolveInfos;
8368    }
8369
8370    @Override
8371    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8372            String resolvedType, int flags, int userId) {
8373        return new ParceledListSlice<>(
8374                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8375    }
8376
8377    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8378            Intent intent, String resolvedType, int flags, int userId) {
8379        if (!sUserManager.exists(userId)) return Collections.emptyList();
8380        final int callingUid = Binder.getCallingUid();
8381        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8382        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8383                false /*includeInstantApps*/);
8384        ComponentName comp = intent.getComponent();
8385        if (comp == null) {
8386            if (intent.getSelector() != null) {
8387                intent = intent.getSelector();
8388                comp = intent.getComponent();
8389            }
8390        }
8391        if (comp != null) {
8392            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8393            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8394            if (pi != null) {
8395                // When specifying an explicit component, we prevent the provider from being
8396                // used when either 1) the provider is in an instant application and the
8397                // caller is not the same instant application or 2) the calling package is an
8398                // instant application and the provider is not visible to instant applications.
8399                final boolean matchInstantApp =
8400                        (flags & PackageManager.MATCH_INSTANT) != 0;
8401                final boolean matchVisibleToInstantAppOnly =
8402                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8403                final boolean isCallerInstantApp =
8404                        instantAppPkgName != null;
8405                final boolean isTargetSameInstantApp =
8406                        comp.getPackageName().equals(instantAppPkgName);
8407                final boolean isTargetInstantApp =
8408                        (pi.applicationInfo.privateFlags
8409                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8410                final boolean isTargetHiddenFromInstantApp =
8411                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8412                final boolean blockResolution =
8413                        !isTargetSameInstantApp
8414                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8415                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8416                                        && isTargetHiddenFromInstantApp));
8417                if (!blockResolution) {
8418                    final ResolveInfo ri = new ResolveInfo();
8419                    ri.providerInfo = pi;
8420                    list.add(ri);
8421                }
8422            }
8423            return list;
8424        }
8425
8426        // reader
8427        synchronized (mPackages) {
8428            String pkgName = intent.getPackage();
8429            if (pkgName == null) {
8430                return applyPostContentProviderResolutionFilter(
8431                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8432                        instantAppPkgName);
8433            }
8434            final PackageParser.Package pkg = mPackages.get(pkgName);
8435            if (pkg != null) {
8436                return applyPostContentProviderResolutionFilter(
8437                        mProviders.queryIntentForPackage(
8438                        intent, resolvedType, flags, pkg.providers, userId),
8439                        instantAppPkgName);
8440            }
8441            return Collections.emptyList();
8442        }
8443    }
8444
8445    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8446            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8447        if (instantAppPkgName == null) {
8448            return resolveInfos;
8449        }
8450        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8451            final ResolveInfo info = resolveInfos.get(i);
8452            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8453            // allow providers that are defined in the provided package
8454            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8455                if (info.providerInfo.splitName != null
8456                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8457                                info.providerInfo.splitName)) {
8458                    // requested provider is defined in a split that hasn't been installed yet.
8459                    // add the installer to the resolve list
8460                    if (DEBUG_EPHEMERAL) {
8461                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8462                    }
8463                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8464                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8465                            info.providerInfo.packageName, info.providerInfo.splitName,
8466                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8467                            null /*failureIntent*/);
8468                    // make sure this resolver is the default
8469                    installerInfo.isDefault = true;
8470                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8471                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8472                    // add a non-generic filter
8473                    installerInfo.filter = new IntentFilter();
8474                    // load resources from the correct package
8475                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8476                    resolveInfos.set(i, installerInfo);
8477                }
8478                continue;
8479            }
8480            // allow providers that have been explicitly exposed to instant applications
8481            if (!isEphemeralApp
8482                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8483                continue;
8484            }
8485            resolveInfos.remove(i);
8486        }
8487        return resolveInfos;
8488    }
8489
8490    @Override
8491    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8492        final int callingUid = Binder.getCallingUid();
8493        if (getInstantAppPackageName(callingUid) != null) {
8494            return ParceledListSlice.emptyList();
8495        }
8496        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8497        flags = updateFlagsForPackage(flags, userId, null);
8498        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8499        enforceCrossUserPermission(callingUid, userId,
8500                true /* requireFullPermission */, false /* checkShell */,
8501                "get installed packages");
8502
8503        // writer
8504        synchronized (mPackages) {
8505            ArrayList<PackageInfo> list;
8506            if (listUninstalled) {
8507                list = new ArrayList<>(mSettings.mPackages.size());
8508                for (PackageSetting ps : mSettings.mPackages.values()) {
8509                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8510                        continue;
8511                    }
8512                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8513                        return null;
8514                    }
8515                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8516                    if (pi != null) {
8517                        list.add(pi);
8518                    }
8519                }
8520            } else {
8521                list = new ArrayList<>(mPackages.size());
8522                for (PackageParser.Package p : mPackages.values()) {
8523                    final PackageSetting ps = (PackageSetting) p.mExtras;
8524                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8525                        continue;
8526                    }
8527                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8528                        return null;
8529                    }
8530                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8531                            p.mExtras, flags, userId);
8532                    if (pi != null) {
8533                        list.add(pi);
8534                    }
8535                }
8536            }
8537
8538            return new ParceledListSlice<>(list);
8539        }
8540    }
8541
8542    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8543            String[] permissions, boolean[] tmp, int flags, int userId) {
8544        int numMatch = 0;
8545        final PermissionsState permissionsState = ps.getPermissionsState();
8546        for (int i=0; i<permissions.length; i++) {
8547            final String permission = permissions[i];
8548            if (permissionsState.hasPermission(permission, userId)) {
8549                tmp[i] = true;
8550                numMatch++;
8551            } else {
8552                tmp[i] = false;
8553            }
8554        }
8555        if (numMatch == 0) {
8556            return;
8557        }
8558        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8559
8560        // The above might return null in cases of uninstalled apps or install-state
8561        // skew across users/profiles.
8562        if (pi != null) {
8563            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8564                if (numMatch == permissions.length) {
8565                    pi.requestedPermissions = permissions;
8566                } else {
8567                    pi.requestedPermissions = new String[numMatch];
8568                    numMatch = 0;
8569                    for (int i=0; i<permissions.length; i++) {
8570                        if (tmp[i]) {
8571                            pi.requestedPermissions[numMatch] = permissions[i];
8572                            numMatch++;
8573                        }
8574                    }
8575                }
8576            }
8577            list.add(pi);
8578        }
8579    }
8580
8581    @Override
8582    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8583            String[] permissions, int flags, int userId) {
8584        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8585        flags = updateFlagsForPackage(flags, userId, permissions);
8586        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8587                true /* requireFullPermission */, false /* checkShell */,
8588                "get packages holding permissions");
8589        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8590
8591        // writer
8592        synchronized (mPackages) {
8593            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8594            boolean[] tmpBools = new boolean[permissions.length];
8595            if (listUninstalled) {
8596                for (PackageSetting ps : mSettings.mPackages.values()) {
8597                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8598                            userId);
8599                }
8600            } else {
8601                for (PackageParser.Package pkg : mPackages.values()) {
8602                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8603                    if (ps != null) {
8604                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8605                                userId);
8606                    }
8607                }
8608            }
8609
8610            return new ParceledListSlice<PackageInfo>(list);
8611        }
8612    }
8613
8614    @Override
8615    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8616        final int callingUid = Binder.getCallingUid();
8617        if (getInstantAppPackageName(callingUid) != null) {
8618            return ParceledListSlice.emptyList();
8619        }
8620        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8621        flags = updateFlagsForApplication(flags, userId, null);
8622        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8623
8624        // writer
8625        synchronized (mPackages) {
8626            ArrayList<ApplicationInfo> list;
8627            if (listUninstalled) {
8628                list = new ArrayList<>(mSettings.mPackages.size());
8629                for (PackageSetting ps : mSettings.mPackages.values()) {
8630                    ApplicationInfo ai;
8631                    int effectiveFlags = flags;
8632                    if (ps.isSystem()) {
8633                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8634                    }
8635                    if (ps.pkg != null) {
8636                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8637                            continue;
8638                        }
8639                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8640                            return null;
8641                        }
8642                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8643                                ps.readUserState(userId), userId);
8644                        if (ai != null) {
8645                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8646                        }
8647                    } else {
8648                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8649                        // and already converts to externally visible package name
8650                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8651                                callingUid, effectiveFlags, userId);
8652                    }
8653                    if (ai != null) {
8654                        list.add(ai);
8655                    }
8656                }
8657            } else {
8658                list = new ArrayList<>(mPackages.size());
8659                for (PackageParser.Package p : mPackages.values()) {
8660                    if (p.mExtras != null) {
8661                        PackageSetting ps = (PackageSetting) p.mExtras;
8662                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8663                            continue;
8664                        }
8665                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8666                            return null;
8667                        }
8668                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8669                                ps.readUserState(userId), userId);
8670                        if (ai != null) {
8671                            ai.packageName = resolveExternalPackageNameLPr(p);
8672                            list.add(ai);
8673                        }
8674                    }
8675                }
8676            }
8677
8678            return new ParceledListSlice<>(list);
8679        }
8680    }
8681
8682    @Override
8683    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8684        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8685            return null;
8686        }
8687        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8688            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8689                    "getEphemeralApplications");
8690        }
8691        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8692                true /* requireFullPermission */, false /* checkShell */,
8693                "getEphemeralApplications");
8694        synchronized (mPackages) {
8695            List<InstantAppInfo> instantApps = mInstantAppRegistry
8696                    .getInstantAppsLPr(userId);
8697            if (instantApps != null) {
8698                return new ParceledListSlice<>(instantApps);
8699            }
8700        }
8701        return null;
8702    }
8703
8704    @Override
8705    public boolean isInstantApp(String packageName, int userId) {
8706        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8707                true /* requireFullPermission */, false /* checkShell */,
8708                "isInstantApp");
8709        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8710            return false;
8711        }
8712
8713        synchronized (mPackages) {
8714            int callingUid = Binder.getCallingUid();
8715            if (Process.isIsolated(callingUid)) {
8716                callingUid = mIsolatedOwners.get(callingUid);
8717            }
8718            final PackageSetting ps = mSettings.mPackages.get(packageName);
8719            PackageParser.Package pkg = mPackages.get(packageName);
8720            final boolean returnAllowed =
8721                    ps != null
8722                    && (isCallerSameApp(packageName, callingUid)
8723                            || canViewInstantApps(callingUid, userId)
8724                            || mInstantAppRegistry.isInstantAccessGranted(
8725                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8726            if (returnAllowed) {
8727                return ps.getInstantApp(userId);
8728            }
8729        }
8730        return false;
8731    }
8732
8733    @Override
8734    public byte[] getInstantAppCookie(String packageName, int userId) {
8735        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8736            return null;
8737        }
8738
8739        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8740                true /* requireFullPermission */, false /* checkShell */,
8741                "getInstantAppCookie");
8742        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8743            return null;
8744        }
8745        synchronized (mPackages) {
8746            return mInstantAppRegistry.getInstantAppCookieLPw(
8747                    packageName, userId);
8748        }
8749    }
8750
8751    @Override
8752    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8753        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8754            return true;
8755        }
8756
8757        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8758                true /* requireFullPermission */, true /* checkShell */,
8759                "setInstantAppCookie");
8760        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8761            return false;
8762        }
8763        synchronized (mPackages) {
8764            return mInstantAppRegistry.setInstantAppCookieLPw(
8765                    packageName, cookie, userId);
8766        }
8767    }
8768
8769    @Override
8770    public Bitmap getInstantAppIcon(String packageName, int userId) {
8771        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8772            return null;
8773        }
8774
8775        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8776            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8777                    "getInstantAppIcon");
8778        }
8779        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8780                true /* requireFullPermission */, false /* checkShell */,
8781                "getInstantAppIcon");
8782
8783        synchronized (mPackages) {
8784            return mInstantAppRegistry.getInstantAppIconLPw(
8785                    packageName, userId);
8786        }
8787    }
8788
8789    private boolean isCallerSameApp(String packageName, int uid) {
8790        PackageParser.Package pkg = mPackages.get(packageName);
8791        return pkg != null
8792                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8793    }
8794
8795    @Override
8796    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8797        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8798            return ParceledListSlice.emptyList();
8799        }
8800        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8801    }
8802
8803    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8804        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8805
8806        // reader
8807        synchronized (mPackages) {
8808            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8809            final int userId = UserHandle.getCallingUserId();
8810            while (i.hasNext()) {
8811                final PackageParser.Package p = i.next();
8812                if (p.applicationInfo == null) continue;
8813
8814                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8815                        && !p.applicationInfo.isDirectBootAware();
8816                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8817                        && p.applicationInfo.isDirectBootAware();
8818
8819                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8820                        && (!mSafeMode || isSystemApp(p))
8821                        && (matchesUnaware || matchesAware)) {
8822                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8823                    if (ps != null) {
8824                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8825                                ps.readUserState(userId), userId);
8826                        if (ai != null) {
8827                            finalList.add(ai);
8828                        }
8829                    }
8830                }
8831            }
8832        }
8833
8834        return finalList;
8835    }
8836
8837    @Override
8838    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8839        if (!sUserManager.exists(userId)) return null;
8840        flags = updateFlagsForComponent(flags, userId, name);
8841        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8842        // reader
8843        synchronized (mPackages) {
8844            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8845            PackageSetting ps = provider != null
8846                    ? mSettings.mPackages.get(provider.owner.packageName)
8847                    : null;
8848            if (ps != null) {
8849                final boolean isInstantApp = ps.getInstantApp(userId);
8850                // normal application; filter out instant application provider
8851                if (instantAppPkgName == null && isInstantApp) {
8852                    return null;
8853                }
8854                // instant application; filter out other instant applications
8855                if (instantAppPkgName != null
8856                        && isInstantApp
8857                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8858                    return null;
8859                }
8860                // instant application; filter out non-exposed provider
8861                if (instantAppPkgName != null
8862                        && !isInstantApp
8863                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8864                    return null;
8865                }
8866                // provider not enabled
8867                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8868                    return null;
8869                }
8870                return PackageParser.generateProviderInfo(
8871                        provider, flags, ps.readUserState(userId), userId);
8872            }
8873            return null;
8874        }
8875    }
8876
8877    /**
8878     * @deprecated
8879     */
8880    @Deprecated
8881    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8882        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8883            return;
8884        }
8885        // reader
8886        synchronized (mPackages) {
8887            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8888                    .entrySet().iterator();
8889            final int userId = UserHandle.getCallingUserId();
8890            while (i.hasNext()) {
8891                Map.Entry<String, PackageParser.Provider> entry = i.next();
8892                PackageParser.Provider p = entry.getValue();
8893                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8894
8895                if (ps != null && p.syncable
8896                        && (!mSafeMode || (p.info.applicationInfo.flags
8897                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8898                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8899                            ps.readUserState(userId), userId);
8900                    if (info != null) {
8901                        outNames.add(entry.getKey());
8902                        outInfo.add(info);
8903                    }
8904                }
8905            }
8906        }
8907    }
8908
8909    @Override
8910    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8911            int uid, int flags, String metaDataKey) {
8912        final int callingUid = Binder.getCallingUid();
8913        final int userId = processName != null ? UserHandle.getUserId(uid)
8914                : UserHandle.getCallingUserId();
8915        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8916        flags = updateFlagsForComponent(flags, userId, processName);
8917        ArrayList<ProviderInfo> finalList = null;
8918        // reader
8919        synchronized (mPackages) {
8920            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8921            while (i.hasNext()) {
8922                final PackageParser.Provider p = i.next();
8923                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8924                if (ps != null && p.info.authority != null
8925                        && (processName == null
8926                                || (p.info.processName.equals(processName)
8927                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8928                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8929
8930                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8931                    // parameter.
8932                    if (metaDataKey != null
8933                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8934                        continue;
8935                    }
8936                    final ComponentName component =
8937                            new ComponentName(p.info.packageName, p.info.name);
8938                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8939                        continue;
8940                    }
8941                    if (finalList == null) {
8942                        finalList = new ArrayList<ProviderInfo>(3);
8943                    }
8944                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8945                            ps.readUserState(userId), userId);
8946                    if (info != null) {
8947                        finalList.add(info);
8948                    }
8949                }
8950            }
8951        }
8952
8953        if (finalList != null) {
8954            Collections.sort(finalList, mProviderInitOrderSorter);
8955            return new ParceledListSlice<ProviderInfo>(finalList);
8956        }
8957
8958        return ParceledListSlice.emptyList();
8959    }
8960
8961    @Override
8962    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8963        // reader
8964        synchronized (mPackages) {
8965            final int callingUid = Binder.getCallingUid();
8966            final int callingUserId = UserHandle.getUserId(callingUid);
8967            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8968            if (ps == null) return null;
8969            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8970                return null;
8971            }
8972            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8973            return PackageParser.generateInstrumentationInfo(i, flags);
8974        }
8975    }
8976
8977    @Override
8978    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8979            String targetPackage, int flags) {
8980        final int callingUid = Binder.getCallingUid();
8981        final int callingUserId = UserHandle.getUserId(callingUid);
8982        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8983        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8984            return ParceledListSlice.emptyList();
8985        }
8986        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8987    }
8988
8989    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8990            int flags) {
8991        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8992
8993        // reader
8994        synchronized (mPackages) {
8995            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8996            while (i.hasNext()) {
8997                final PackageParser.Instrumentation p = i.next();
8998                if (targetPackage == null
8999                        || targetPackage.equals(p.info.targetPackage)) {
9000                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
9001                            flags);
9002                    if (ii != null) {
9003                        finalList.add(ii);
9004                    }
9005                }
9006            }
9007        }
9008
9009        return finalList;
9010    }
9011
9012    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9013        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9014        try {
9015            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9016        } finally {
9017            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9018        }
9019    }
9020
9021    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9022        final File[] files = dir.listFiles();
9023        if (ArrayUtils.isEmpty(files)) {
9024            Log.d(TAG, "No files in app dir " + dir);
9025            return;
9026        }
9027
9028        if (DEBUG_PACKAGE_SCANNING) {
9029            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9030                    + " flags=0x" + Integer.toHexString(parseFlags));
9031        }
9032        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9033                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9034                mParallelPackageParserCallback);
9035
9036        // Submit files for parsing in parallel
9037        int fileCount = 0;
9038        for (File file : files) {
9039            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9040                    && !PackageInstallerService.isStageName(file.getName());
9041            if (!isPackage) {
9042                // Ignore entries which are not packages
9043                continue;
9044            }
9045            parallelPackageParser.submit(file, parseFlags);
9046            fileCount++;
9047        }
9048
9049        // Process results one by one
9050        for (; fileCount > 0; fileCount--) {
9051            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9052            Throwable throwable = parseResult.throwable;
9053            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9054
9055            if (throwable == null) {
9056                // Static shared libraries have synthetic package names
9057                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9058                    renameStaticSharedLibraryPackage(parseResult.pkg);
9059                }
9060                try {
9061                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9062                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9063                                currentTime, null);
9064                    }
9065                } catch (PackageManagerException e) {
9066                    errorCode = e.error;
9067                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9068                }
9069            } else if (throwable instanceof PackageParser.PackageParserException) {
9070                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9071                        throwable;
9072                errorCode = e.error;
9073                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9074            } else {
9075                throw new IllegalStateException("Unexpected exception occurred while parsing "
9076                        + parseResult.scanFile, throwable);
9077            }
9078
9079            // Delete invalid userdata apps
9080            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9081                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9082                logCriticalInfo(Log.WARN,
9083                        "Deleting invalid package at " + parseResult.scanFile);
9084                removeCodePathLI(parseResult.scanFile);
9085            }
9086        }
9087        parallelPackageParser.close();
9088    }
9089
9090    private static File getSettingsProblemFile() {
9091        File dataDir = Environment.getDataDirectory();
9092        File systemDir = new File(dataDir, "system");
9093        File fname = new File(systemDir, "uiderrors.txt");
9094        return fname;
9095    }
9096
9097    static void reportSettingsProblem(int priority, String msg) {
9098        logCriticalInfo(priority, msg);
9099    }
9100
9101    public static void logCriticalInfo(int priority, String msg) {
9102        Slog.println(priority, TAG, msg);
9103        EventLogTags.writePmCriticalInfo(msg);
9104        try {
9105            File fname = getSettingsProblemFile();
9106            FileOutputStream out = new FileOutputStream(fname, true);
9107            PrintWriter pw = new FastPrintWriter(out);
9108            SimpleDateFormat formatter = new SimpleDateFormat();
9109            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9110            pw.println(dateString + ": " + msg);
9111            pw.close();
9112            FileUtils.setPermissions(
9113                    fname.toString(),
9114                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9115                    -1, -1);
9116        } catch (java.io.IOException e) {
9117        }
9118    }
9119
9120    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9121        if (srcFile.isDirectory()) {
9122            final File baseFile = new File(pkg.baseCodePath);
9123            long maxModifiedTime = baseFile.lastModified();
9124            if (pkg.splitCodePaths != null) {
9125                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9126                    final File splitFile = new File(pkg.splitCodePaths[i]);
9127                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9128                }
9129            }
9130            return maxModifiedTime;
9131        }
9132        return srcFile.lastModified();
9133    }
9134
9135    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9136            final int policyFlags) throws PackageManagerException {
9137        // When upgrading from pre-N MR1, verify the package time stamp using the package
9138        // directory and not the APK file.
9139        final long lastModifiedTime = mIsPreNMR1Upgrade
9140                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9141        if (ps != null
9142                && ps.codePath.equals(srcFile)
9143                && ps.timeStamp == lastModifiedTime
9144                && !isCompatSignatureUpdateNeeded(pkg)
9145                && !isRecoverSignatureUpdateNeeded(pkg)) {
9146            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9147            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9148            ArraySet<PublicKey> signingKs;
9149            synchronized (mPackages) {
9150                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9151            }
9152            if (ps.signatures.mSignatures != null
9153                    && ps.signatures.mSignatures.length != 0
9154                    && signingKs != null) {
9155                // Optimization: reuse the existing cached certificates
9156                // if the package appears to be unchanged.
9157                pkg.mSignatures = ps.signatures.mSignatures;
9158                pkg.mSigningKeys = signingKs;
9159                return;
9160            }
9161
9162            Slog.w(TAG, "PackageSetting for " + ps.name
9163                    + " is missing signatures.  Collecting certs again to recover them.");
9164        } else {
9165            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9166        }
9167
9168        try {
9169            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9170            PackageParser.collectCertificates(pkg, policyFlags);
9171        } catch (PackageParserException e) {
9172            throw PackageManagerException.from(e);
9173        } finally {
9174            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9175        }
9176    }
9177
9178    /**
9179     *  Traces a package scan.
9180     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9181     */
9182    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9183            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9184        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9185        try {
9186            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9187        } finally {
9188            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9189        }
9190    }
9191
9192    /**
9193     *  Scans a package and returns the newly parsed package.
9194     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9195     */
9196    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9197            long currentTime, UserHandle user) throws PackageManagerException {
9198        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9199        PackageParser pp = new PackageParser();
9200        pp.setSeparateProcesses(mSeparateProcesses);
9201        pp.setOnlyCoreApps(mOnlyCore);
9202        pp.setDisplayMetrics(mMetrics);
9203        pp.setCallback(mPackageParserCallback);
9204
9205        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9206            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9207        }
9208
9209        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9210        final PackageParser.Package pkg;
9211        try {
9212            pkg = pp.parsePackage(scanFile, parseFlags);
9213        } catch (PackageParserException e) {
9214            throw PackageManagerException.from(e);
9215        } finally {
9216            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9217        }
9218
9219        // Static shared libraries have synthetic package names
9220        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9221            renameStaticSharedLibraryPackage(pkg);
9222        }
9223
9224        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9225    }
9226
9227    /**
9228     *  Scans a package and returns the newly parsed package.
9229     *  @throws PackageManagerException on a parse error.
9230     */
9231    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9232            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9233            throws PackageManagerException {
9234        // If the package has children and this is the first dive in the function
9235        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9236        // packages (parent and children) would be successfully scanned before the
9237        // actual scan since scanning mutates internal state and we want to atomically
9238        // install the package and its children.
9239        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9240            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9241                scanFlags |= SCAN_CHECK_ONLY;
9242            }
9243        } else {
9244            scanFlags &= ~SCAN_CHECK_ONLY;
9245        }
9246
9247        // Scan the parent
9248        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9249                scanFlags, currentTime, user);
9250
9251        // Scan the children
9252        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9253        for (int i = 0; i < childCount; i++) {
9254            PackageParser.Package childPackage = pkg.childPackages.get(i);
9255            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9256                    currentTime, user);
9257        }
9258
9259
9260        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9261            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9262        }
9263
9264        return scannedPkg;
9265    }
9266
9267    /**
9268     *  Scans a package and returns the newly parsed package.
9269     *  @throws PackageManagerException on a parse error.
9270     */
9271    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9272            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9273            throws PackageManagerException {
9274        PackageSetting ps = null;
9275        PackageSetting updatedPkg;
9276        // reader
9277        synchronized (mPackages) {
9278            // Look to see if we already know about this package.
9279            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9280            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9281                // This package has been renamed to its original name.  Let's
9282                // use that.
9283                ps = mSettings.getPackageLPr(oldName);
9284            }
9285            // If there was no original package, see one for the real package name.
9286            if (ps == null) {
9287                ps = mSettings.getPackageLPr(pkg.packageName);
9288            }
9289            // Check to see if this package could be hiding/updating a system
9290            // package.  Must look for it either under the original or real
9291            // package name depending on our state.
9292            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9293            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9294
9295            // If this is a package we don't know about on the system partition, we
9296            // may need to remove disabled child packages on the system partition
9297            // or may need to not add child packages if the parent apk is updated
9298            // on the data partition and no longer defines this child package.
9299            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9300                // If this is a parent package for an updated system app and this system
9301                // app got an OTA update which no longer defines some of the child packages
9302                // we have to prune them from the disabled system packages.
9303                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9304                if (disabledPs != null) {
9305                    final int scannedChildCount = (pkg.childPackages != null)
9306                            ? pkg.childPackages.size() : 0;
9307                    final int disabledChildCount = disabledPs.childPackageNames != null
9308                            ? disabledPs.childPackageNames.size() : 0;
9309                    for (int i = 0; i < disabledChildCount; i++) {
9310                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9311                        boolean disabledPackageAvailable = false;
9312                        for (int j = 0; j < scannedChildCount; j++) {
9313                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9314                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9315                                disabledPackageAvailable = true;
9316                                break;
9317                            }
9318                         }
9319                         if (!disabledPackageAvailable) {
9320                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9321                         }
9322                    }
9323                }
9324            }
9325        }
9326
9327        final boolean isUpdatedPkg = updatedPkg != null;
9328        final boolean isUpdatedSystemPkg = isUpdatedPkg
9329                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9330        boolean isUpdatedPkgBetter = false;
9331        // First check if this is a system package that may involve an update
9332        if (isUpdatedSystemPkg) {
9333            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9334            // it needs to drop FLAG_PRIVILEGED.
9335            if (locationIsPrivileged(scanFile)) {
9336                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9337            } else {
9338                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9339            }
9340
9341            if (ps != null && !ps.codePath.equals(scanFile)) {
9342                // The path has changed from what was last scanned...  check the
9343                // version of the new path against what we have stored to determine
9344                // what to do.
9345                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9346                if (pkg.mVersionCode <= ps.versionCode) {
9347                    // The system package has been updated and the code path does not match
9348                    // Ignore entry. Skip it.
9349                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9350                            + " ignored: updated version " + ps.versionCode
9351                            + " better than this " + pkg.mVersionCode);
9352                    if (!updatedPkg.codePath.equals(scanFile)) {
9353                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9354                                + ps.name + " changing from " + updatedPkg.codePathString
9355                                + " to " + scanFile);
9356                        updatedPkg.codePath = scanFile;
9357                        updatedPkg.codePathString = scanFile.toString();
9358                        updatedPkg.resourcePath = scanFile;
9359                        updatedPkg.resourcePathString = scanFile.toString();
9360                    }
9361                    updatedPkg.pkg = pkg;
9362                    updatedPkg.versionCode = pkg.mVersionCode;
9363
9364                    // Update the disabled system child packages to point to the package too.
9365                    final int childCount = updatedPkg.childPackageNames != null
9366                            ? updatedPkg.childPackageNames.size() : 0;
9367                    for (int i = 0; i < childCount; i++) {
9368                        String childPackageName = updatedPkg.childPackageNames.get(i);
9369                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9370                                childPackageName);
9371                        if (updatedChildPkg != null) {
9372                            updatedChildPkg.pkg = pkg;
9373                            updatedChildPkg.versionCode = pkg.mVersionCode;
9374                        }
9375                    }
9376                } else {
9377                    // The current app on the system partition is better than
9378                    // what we have updated to on the data partition; switch
9379                    // back to the system partition version.
9380                    // At this point, its safely assumed that package installation for
9381                    // apps in system partition will go through. If not there won't be a working
9382                    // version of the app
9383                    // writer
9384                    synchronized (mPackages) {
9385                        // Just remove the loaded entries from package lists.
9386                        mPackages.remove(ps.name);
9387                    }
9388
9389                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9390                            + " reverting from " + ps.codePathString
9391                            + ": new version " + pkg.mVersionCode
9392                            + " better than installed " + ps.versionCode);
9393
9394                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9395                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9396                    synchronized (mInstallLock) {
9397                        args.cleanUpResourcesLI();
9398                    }
9399                    synchronized (mPackages) {
9400                        mSettings.enableSystemPackageLPw(ps.name);
9401                    }
9402                    isUpdatedPkgBetter = true;
9403                }
9404            }
9405        }
9406
9407        String resourcePath = null;
9408        String baseResourcePath = null;
9409        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9410            if (ps != null && ps.resourcePathString != null) {
9411                resourcePath = ps.resourcePathString;
9412                baseResourcePath = ps.resourcePathString;
9413            } else {
9414                // Should not happen at all. Just log an error.
9415                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9416            }
9417        } else {
9418            resourcePath = pkg.codePath;
9419            baseResourcePath = pkg.baseCodePath;
9420        }
9421
9422        // Set application objects path explicitly.
9423        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9424        pkg.setApplicationInfoCodePath(pkg.codePath);
9425        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9426        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9427        pkg.setApplicationInfoResourcePath(resourcePath);
9428        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9429        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9430
9431        // throw an exception if we have an update to a system application, but, it's not more
9432        // recent than the package we've already scanned
9433        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9434            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9435                    + scanFile + " ignored: updated version " + ps.versionCode
9436                    + " better than this " + pkg.mVersionCode);
9437        }
9438
9439        if (isUpdatedPkg) {
9440            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9441            // initially
9442            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9443
9444            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9445            // flag set initially
9446            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9447                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9448            }
9449        }
9450
9451        // Verify certificates against what was last scanned
9452        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9453
9454        /*
9455         * A new system app appeared, but we already had a non-system one of the
9456         * same name installed earlier.
9457         */
9458        boolean shouldHideSystemApp = false;
9459        if (!isUpdatedPkg && ps != null
9460                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9461            /*
9462             * Check to make sure the signatures match first. If they don't,
9463             * wipe the installed application and its data.
9464             */
9465            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9466                    != PackageManager.SIGNATURE_MATCH) {
9467                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9468                        + " signatures don't match existing userdata copy; removing");
9469                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9470                        "scanPackageInternalLI")) {
9471                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9472                }
9473                ps = null;
9474            } else {
9475                /*
9476                 * If the newly-added system app is an older version than the
9477                 * already installed version, hide it. It will be scanned later
9478                 * and re-added like an update.
9479                 */
9480                if (pkg.mVersionCode <= ps.versionCode) {
9481                    shouldHideSystemApp = true;
9482                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9483                            + " but new version " + pkg.mVersionCode + " better than installed "
9484                            + ps.versionCode + "; hiding system");
9485                } else {
9486                    /*
9487                     * The newly found system app is a newer version that the
9488                     * one previously installed. Simply remove the
9489                     * already-installed application and replace it with our own
9490                     * while keeping the application data.
9491                     */
9492                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9493                            + " reverting from " + ps.codePathString + ": new version "
9494                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9495                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9496                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9497                    synchronized (mInstallLock) {
9498                        args.cleanUpResourcesLI();
9499                    }
9500                }
9501            }
9502        }
9503
9504        // The apk is forward locked (not public) if its code and resources
9505        // are kept in different files. (except for app in either system or
9506        // vendor path).
9507        // TODO grab this value from PackageSettings
9508        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9509            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9510                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9511            }
9512        }
9513
9514        final int userId = ((user == null) ? 0 : user.getIdentifier());
9515        if (ps != null && ps.getInstantApp(userId)) {
9516            scanFlags |= SCAN_AS_INSTANT_APP;
9517        }
9518        if (ps != null && ps.getVirtulalPreload(userId)) {
9519            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9520        }
9521
9522        // Note that we invoke the following method only if we are about to unpack an application
9523        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9524                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9525
9526        /*
9527         * If the system app should be overridden by a previously installed
9528         * data, hide the system app now and let the /data/app scan pick it up
9529         * again.
9530         */
9531        if (shouldHideSystemApp) {
9532            synchronized (mPackages) {
9533                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9534            }
9535        }
9536
9537        return scannedPkg;
9538    }
9539
9540    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9541        // Derive the new package synthetic package name
9542        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9543                + pkg.staticSharedLibVersion);
9544    }
9545
9546    private static String fixProcessName(String defProcessName,
9547            String processName) {
9548        if (processName == null) {
9549            return defProcessName;
9550        }
9551        return processName;
9552    }
9553
9554    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9555            throws PackageManagerException {
9556        if (pkgSetting.signatures.mSignatures != null) {
9557            // Already existing package. Make sure signatures match
9558            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9559                    == PackageManager.SIGNATURE_MATCH;
9560            if (!match) {
9561                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9562                        == PackageManager.SIGNATURE_MATCH;
9563            }
9564            if (!match) {
9565                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9566                        == PackageManager.SIGNATURE_MATCH;
9567            }
9568            if (!match) {
9569                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9570                        + pkg.packageName + " signatures do not match the "
9571                        + "previously installed version; ignoring!");
9572            }
9573        }
9574
9575        // Check for shared user signatures
9576        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9577            // Already existing package. Make sure signatures match
9578            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9579                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9580            if (!match) {
9581                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9582                        == PackageManager.SIGNATURE_MATCH;
9583            }
9584            if (!match) {
9585                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9586                        == PackageManager.SIGNATURE_MATCH;
9587            }
9588            if (!match) {
9589                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9590                        "Package " + pkg.packageName
9591                        + " has no signatures that match those in shared user "
9592                        + pkgSetting.sharedUser.name + "; ignoring!");
9593            }
9594        }
9595    }
9596
9597    /**
9598     * Enforces that only the system UID or root's UID can call a method exposed
9599     * via Binder.
9600     *
9601     * @param message used as message if SecurityException is thrown
9602     * @throws SecurityException if the caller is not system or root
9603     */
9604    private static final void enforceSystemOrRoot(String message) {
9605        final int uid = Binder.getCallingUid();
9606        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9607            throw new SecurityException(message);
9608        }
9609    }
9610
9611    @Override
9612    public void performFstrimIfNeeded() {
9613        enforceSystemOrRoot("Only the system can request fstrim");
9614
9615        // Before everything else, see whether we need to fstrim.
9616        try {
9617            IStorageManager sm = PackageHelper.getStorageManager();
9618            if (sm != null) {
9619                boolean doTrim = false;
9620                final long interval = android.provider.Settings.Global.getLong(
9621                        mContext.getContentResolver(),
9622                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9623                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9624                if (interval > 0) {
9625                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9626                    if (timeSinceLast > interval) {
9627                        doTrim = true;
9628                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9629                                + "; running immediately");
9630                    }
9631                }
9632                if (doTrim) {
9633                    final boolean dexOptDialogShown;
9634                    synchronized (mPackages) {
9635                        dexOptDialogShown = mDexOptDialogShown;
9636                    }
9637                    if (!isFirstBoot() && dexOptDialogShown) {
9638                        try {
9639                            ActivityManager.getService().showBootMessage(
9640                                    mContext.getResources().getString(
9641                                            R.string.android_upgrading_fstrim), true);
9642                        } catch (RemoteException e) {
9643                        }
9644                    }
9645                    sm.runMaintenance();
9646                }
9647            } else {
9648                Slog.e(TAG, "storageManager service unavailable!");
9649            }
9650        } catch (RemoteException e) {
9651            // Can't happen; StorageManagerService is local
9652        }
9653    }
9654
9655    @Override
9656    public void updatePackagesIfNeeded() {
9657        enforceSystemOrRoot("Only the system can request package update");
9658
9659        // We need to re-extract after an OTA.
9660        boolean causeUpgrade = isUpgrade();
9661
9662        // First boot or factory reset.
9663        // Note: we also handle devices that are upgrading to N right now as if it is their
9664        //       first boot, as they do not have profile data.
9665        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9666
9667        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9668        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9669
9670        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9671            return;
9672        }
9673
9674        List<PackageParser.Package> pkgs;
9675        synchronized (mPackages) {
9676            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9677        }
9678
9679        final long startTime = System.nanoTime();
9680        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9681                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9682                    false /* bootComplete */);
9683
9684        final int elapsedTimeSeconds =
9685                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9686
9687        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9688        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9689        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9690        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9691        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9692    }
9693
9694    /*
9695     * Return the prebuilt profile path given a package base code path.
9696     */
9697    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9698        return pkg.baseCodePath + ".prof";
9699    }
9700
9701    /**
9702     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9703     * containing statistics about the invocation. The array consists of three elements,
9704     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9705     * and {@code numberOfPackagesFailed}.
9706     */
9707    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9708            String compilerFilter, boolean bootComplete) {
9709
9710        int numberOfPackagesVisited = 0;
9711        int numberOfPackagesOptimized = 0;
9712        int numberOfPackagesSkipped = 0;
9713        int numberOfPackagesFailed = 0;
9714        final int numberOfPackagesToDexopt = pkgs.size();
9715
9716        for (PackageParser.Package pkg : pkgs) {
9717            numberOfPackagesVisited++;
9718
9719            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9720                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9721                // that are already compiled.
9722                File profileFile = new File(getPrebuildProfilePath(pkg));
9723                // Copy profile if it exists.
9724                if (profileFile.exists()) {
9725                    try {
9726                        // We could also do this lazily before calling dexopt in
9727                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9728                        // is that we don't have a good way to say "do this only once".
9729                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9730                                pkg.applicationInfo.uid, pkg.packageName)) {
9731                            Log.e(TAG, "Installer failed to copy system profile!");
9732                        }
9733                    } catch (Exception e) {
9734                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9735                                e);
9736                    }
9737                }
9738            }
9739
9740            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9741                if (DEBUG_DEXOPT) {
9742                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9743                }
9744                numberOfPackagesSkipped++;
9745                continue;
9746            }
9747
9748            if (DEBUG_DEXOPT) {
9749                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9750                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9751            }
9752
9753            if (showDialog) {
9754                try {
9755                    ActivityManager.getService().showBootMessage(
9756                            mContext.getResources().getString(R.string.android_upgrading_apk,
9757                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9758                } catch (RemoteException e) {
9759                }
9760                synchronized (mPackages) {
9761                    mDexOptDialogShown = true;
9762                }
9763            }
9764
9765            // If the OTA updates a system app which was previously preopted to a non-preopted state
9766            // the app might end up being verified at runtime. That's because by default the apps
9767            // are verify-profile but for preopted apps there's no profile.
9768            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9769            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9770            // filter (by default 'quicken').
9771            // Note that at this stage unused apps are already filtered.
9772            if (isSystemApp(pkg) &&
9773                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9774                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9775                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9776            }
9777
9778            // checkProfiles is false to avoid merging profiles during boot which
9779            // might interfere with background compilation (b/28612421).
9780            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9781            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9782            // trade-off worth doing to save boot time work.
9783            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9784            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9785                    pkg.packageName,
9786                    compilerFilter,
9787                    dexoptFlags));
9788
9789            if (pkg.isSystemApp()) {
9790                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9791                // too much boot after an OTA.
9792                int secondaryDexoptFlags = dexoptFlags |
9793                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9794                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9795                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9796                        pkg.packageName,
9797                        compilerFilter,
9798                        secondaryDexoptFlags));
9799            }
9800
9801            // TODO(shubhamajmera): Record secondary dexopt stats.
9802            switch (primaryDexOptStaus) {
9803                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9804                    numberOfPackagesOptimized++;
9805                    break;
9806                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9807                    numberOfPackagesSkipped++;
9808                    break;
9809                case PackageDexOptimizer.DEX_OPT_FAILED:
9810                    numberOfPackagesFailed++;
9811                    break;
9812                default:
9813                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9814                    break;
9815            }
9816        }
9817
9818        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9819                numberOfPackagesFailed };
9820    }
9821
9822    @Override
9823    public void notifyPackageUse(String packageName, int reason) {
9824        synchronized (mPackages) {
9825            final int callingUid = Binder.getCallingUid();
9826            final int callingUserId = UserHandle.getUserId(callingUid);
9827            if (getInstantAppPackageName(callingUid) != null) {
9828                if (!isCallerSameApp(packageName, callingUid)) {
9829                    return;
9830                }
9831            } else {
9832                if (isInstantApp(packageName, callingUserId)) {
9833                    return;
9834                }
9835            }
9836            final PackageParser.Package p = mPackages.get(packageName);
9837            if (p == null) {
9838                return;
9839            }
9840            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9841        }
9842    }
9843
9844    @Override
9845    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9846            List<String> classPaths, String loaderIsa) {
9847        int userId = UserHandle.getCallingUserId();
9848        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9849        if (ai == null) {
9850            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9851                + loadingPackageName + ", user=" + userId);
9852            return;
9853        }
9854        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9855    }
9856
9857    @Override
9858    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9859            IDexModuleRegisterCallback callback) {
9860        int userId = UserHandle.getCallingUserId();
9861        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9862        DexManager.RegisterDexModuleResult result;
9863        if (ai == null) {
9864            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9865                     " calling user. package=" + packageName + ", user=" + userId);
9866            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9867        } else {
9868            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9869        }
9870
9871        if (callback != null) {
9872            mHandler.post(() -> {
9873                try {
9874                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9875                } catch (RemoteException e) {
9876                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9877                }
9878            });
9879        }
9880    }
9881
9882    /**
9883     * Ask the package manager to perform a dex-opt with the given compiler filter.
9884     *
9885     * Note: exposed only for the shell command to allow moving packages explicitly to a
9886     *       definite state.
9887     */
9888    @Override
9889    public boolean performDexOptMode(String packageName,
9890            boolean checkProfiles, String targetCompilerFilter, boolean force,
9891            boolean bootComplete, String splitName) {
9892        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9893                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9894                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9895        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9896                splitName, flags));
9897    }
9898
9899    /**
9900     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9901     * secondary dex files belonging to the given package.
9902     *
9903     * Note: exposed only for the shell command to allow moving packages explicitly to a
9904     *       definite state.
9905     */
9906    @Override
9907    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9908            boolean force) {
9909        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9910                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9911                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9912                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9913        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9914    }
9915
9916    /*package*/ boolean performDexOpt(DexoptOptions options) {
9917        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9918            return false;
9919        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9920            return false;
9921        }
9922
9923        if (options.isDexoptOnlySecondaryDex()) {
9924            return mDexManager.dexoptSecondaryDex(options);
9925        } else {
9926            int dexoptStatus = performDexOptWithStatus(options);
9927            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9928        }
9929    }
9930
9931    /**
9932     * Perform dexopt on the given package and return one of following result:
9933     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9934     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9935     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9936     */
9937    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9938        return performDexOptTraced(options);
9939    }
9940
9941    private int performDexOptTraced(DexoptOptions options) {
9942        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9943        try {
9944            return performDexOptInternal(options);
9945        } finally {
9946            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9947        }
9948    }
9949
9950    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9951    // if the package can now be considered up to date for the given filter.
9952    private int performDexOptInternal(DexoptOptions options) {
9953        PackageParser.Package p;
9954        synchronized (mPackages) {
9955            p = mPackages.get(options.getPackageName());
9956            if (p == null) {
9957                // Package could not be found. Report failure.
9958                return PackageDexOptimizer.DEX_OPT_FAILED;
9959            }
9960            mPackageUsage.maybeWriteAsync(mPackages);
9961            mCompilerStats.maybeWriteAsync();
9962        }
9963        long callingId = Binder.clearCallingIdentity();
9964        try {
9965            synchronized (mInstallLock) {
9966                return performDexOptInternalWithDependenciesLI(p, options);
9967            }
9968        } finally {
9969            Binder.restoreCallingIdentity(callingId);
9970        }
9971    }
9972
9973    public ArraySet<String> getOptimizablePackages() {
9974        ArraySet<String> pkgs = new ArraySet<String>();
9975        synchronized (mPackages) {
9976            for (PackageParser.Package p : mPackages.values()) {
9977                if (PackageDexOptimizer.canOptimizePackage(p)) {
9978                    pkgs.add(p.packageName);
9979                }
9980            }
9981        }
9982        return pkgs;
9983    }
9984
9985    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9986            DexoptOptions options) {
9987        // Select the dex optimizer based on the force parameter.
9988        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9989        //       allocate an object here.
9990        PackageDexOptimizer pdo = options.isForce()
9991                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9992                : mPackageDexOptimizer;
9993
9994        // Dexopt all dependencies first. Note: we ignore the return value and march on
9995        // on errors.
9996        // Note that we are going to call performDexOpt on those libraries as many times as
9997        // they are referenced in packages. When we do a batch of performDexOpt (for example
9998        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9999        // and the first package that uses the library will dexopt it. The
10000        // others will see that the compiled code for the library is up to date.
10001        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
10002        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10003        if (!deps.isEmpty()) {
10004            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10005                    options.getCompilerFilter(), options.getSplitName(),
10006                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10007            for (PackageParser.Package depPackage : deps) {
10008                // TODO: Analyze and investigate if we (should) profile libraries.
10009                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10010                        getOrCreateCompilerPackageStats(depPackage),
10011                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10012            }
10013        }
10014        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10015                getOrCreateCompilerPackageStats(p),
10016                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10017    }
10018
10019    /**
10020     * Reconcile the information we have about the secondary dex files belonging to
10021     * {@code packagName} and the actual dex files. For all dex files that were
10022     * deleted, update the internal records and delete the generated oat files.
10023     */
10024    @Override
10025    public void reconcileSecondaryDexFiles(String packageName) {
10026        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10027            return;
10028        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10029            return;
10030        }
10031        mDexManager.reconcileSecondaryDexFiles(packageName);
10032    }
10033
10034    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10035    // a reference there.
10036    /*package*/ DexManager getDexManager() {
10037        return mDexManager;
10038    }
10039
10040    /**
10041     * Execute the background dexopt job immediately.
10042     */
10043    @Override
10044    public boolean runBackgroundDexoptJob() {
10045        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10046            return false;
10047        }
10048        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10049    }
10050
10051    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10052        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10053                || p.usesStaticLibraries != null) {
10054            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10055            Set<String> collectedNames = new HashSet<>();
10056            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10057
10058            retValue.remove(p);
10059
10060            return retValue;
10061        } else {
10062            return Collections.emptyList();
10063        }
10064    }
10065
10066    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10067            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10068        if (!collectedNames.contains(p.packageName)) {
10069            collectedNames.add(p.packageName);
10070            collected.add(p);
10071
10072            if (p.usesLibraries != null) {
10073                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10074                        null, collected, collectedNames);
10075            }
10076            if (p.usesOptionalLibraries != null) {
10077                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10078                        null, collected, collectedNames);
10079            }
10080            if (p.usesStaticLibraries != null) {
10081                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10082                        p.usesStaticLibrariesVersions, collected, collectedNames);
10083            }
10084        }
10085    }
10086
10087    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10088            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10089        final int libNameCount = libs.size();
10090        for (int i = 0; i < libNameCount; i++) {
10091            String libName = libs.get(i);
10092            int version = (versions != null && versions.length == libNameCount)
10093                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10094            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10095            if (libPkg != null) {
10096                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10097            }
10098        }
10099    }
10100
10101    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10102        synchronized (mPackages) {
10103            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10104            if (libEntry != null) {
10105                return mPackages.get(libEntry.apk);
10106            }
10107            return null;
10108        }
10109    }
10110
10111    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10112        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10113        if (versionedLib == null) {
10114            return null;
10115        }
10116        return versionedLib.get(version);
10117    }
10118
10119    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10120        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10121                pkg.staticSharedLibName);
10122        if (versionedLib == null) {
10123            return null;
10124        }
10125        int previousLibVersion = -1;
10126        final int versionCount = versionedLib.size();
10127        for (int i = 0; i < versionCount; i++) {
10128            final int libVersion = versionedLib.keyAt(i);
10129            if (libVersion < pkg.staticSharedLibVersion) {
10130                previousLibVersion = Math.max(previousLibVersion, libVersion);
10131            }
10132        }
10133        if (previousLibVersion >= 0) {
10134            return versionedLib.get(previousLibVersion);
10135        }
10136        return null;
10137    }
10138
10139    public void shutdown() {
10140        mPackageUsage.writeNow(mPackages);
10141        mCompilerStats.writeNow();
10142        mDexManager.writePackageDexUsageNow();
10143    }
10144
10145    @Override
10146    public void dumpProfiles(String packageName) {
10147        PackageParser.Package pkg;
10148        synchronized (mPackages) {
10149            pkg = mPackages.get(packageName);
10150            if (pkg == null) {
10151                throw new IllegalArgumentException("Unknown package: " + packageName);
10152            }
10153        }
10154        /* Only the shell, root, or the app user should be able to dump profiles. */
10155        int callingUid = Binder.getCallingUid();
10156        if (callingUid != Process.SHELL_UID &&
10157            callingUid != Process.ROOT_UID &&
10158            callingUid != pkg.applicationInfo.uid) {
10159            throw new SecurityException("dumpProfiles");
10160        }
10161
10162        synchronized (mInstallLock) {
10163            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10164            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10165            try {
10166                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10167                String codePaths = TextUtils.join(";", allCodePaths);
10168                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10169            } catch (InstallerException e) {
10170                Slog.w(TAG, "Failed to dump profiles", e);
10171            }
10172            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10173        }
10174    }
10175
10176    @Override
10177    public void forceDexOpt(String packageName) {
10178        enforceSystemOrRoot("forceDexOpt");
10179
10180        PackageParser.Package pkg;
10181        synchronized (mPackages) {
10182            pkg = mPackages.get(packageName);
10183            if (pkg == null) {
10184                throw new IllegalArgumentException("Unknown package: " + packageName);
10185            }
10186        }
10187
10188        synchronized (mInstallLock) {
10189            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10190
10191            // Whoever is calling forceDexOpt wants a compiled package.
10192            // Don't use profiles since that may cause compilation to be skipped.
10193            final int res = performDexOptInternalWithDependenciesLI(
10194                    pkg,
10195                    new DexoptOptions(packageName,
10196                            getDefaultCompilerFilter(),
10197                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10198
10199            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10200            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10201                throw new IllegalStateException("Failed to dexopt: " + res);
10202            }
10203        }
10204    }
10205
10206    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10207        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10208            Slog.w(TAG, "Unable to update from " + oldPkg.name
10209                    + " to " + newPkg.packageName
10210                    + ": old package not in system partition");
10211            return false;
10212        } else if (mPackages.get(oldPkg.name) != null) {
10213            Slog.w(TAG, "Unable to update from " + oldPkg.name
10214                    + " to " + newPkg.packageName
10215                    + ": old package still exists");
10216            return false;
10217        }
10218        return true;
10219    }
10220
10221    void removeCodePathLI(File codePath) {
10222        if (codePath.isDirectory()) {
10223            try {
10224                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10225            } catch (InstallerException e) {
10226                Slog.w(TAG, "Failed to remove code path", e);
10227            }
10228        } else {
10229            codePath.delete();
10230        }
10231    }
10232
10233    private int[] resolveUserIds(int userId) {
10234        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10235    }
10236
10237    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10238        if (pkg == null) {
10239            Slog.wtf(TAG, "Package was null!", new Throwable());
10240            return;
10241        }
10242        clearAppDataLeafLIF(pkg, userId, flags);
10243        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10244        for (int i = 0; i < childCount; i++) {
10245            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10246        }
10247    }
10248
10249    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10250        final PackageSetting ps;
10251        synchronized (mPackages) {
10252            ps = mSettings.mPackages.get(pkg.packageName);
10253        }
10254        for (int realUserId : resolveUserIds(userId)) {
10255            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10256            try {
10257                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10258                        ceDataInode);
10259            } catch (InstallerException e) {
10260                Slog.w(TAG, String.valueOf(e));
10261            }
10262        }
10263    }
10264
10265    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10266        if (pkg == null) {
10267            Slog.wtf(TAG, "Package was null!", new Throwable());
10268            return;
10269        }
10270        destroyAppDataLeafLIF(pkg, userId, flags);
10271        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10272        for (int i = 0; i < childCount; i++) {
10273            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10274        }
10275    }
10276
10277    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10278        final PackageSetting ps;
10279        synchronized (mPackages) {
10280            ps = mSettings.mPackages.get(pkg.packageName);
10281        }
10282        for (int realUserId : resolveUserIds(userId)) {
10283            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10284            try {
10285                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10286                        ceDataInode);
10287            } catch (InstallerException e) {
10288                Slog.w(TAG, String.valueOf(e));
10289            }
10290            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10291        }
10292    }
10293
10294    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10295        if (pkg == null) {
10296            Slog.wtf(TAG, "Package was null!", new Throwable());
10297            return;
10298        }
10299        destroyAppProfilesLeafLIF(pkg);
10300        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10301        for (int i = 0; i < childCount; i++) {
10302            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10303        }
10304    }
10305
10306    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10307        try {
10308            mInstaller.destroyAppProfiles(pkg.packageName);
10309        } catch (InstallerException e) {
10310            Slog.w(TAG, String.valueOf(e));
10311        }
10312    }
10313
10314    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10315        if (pkg == null) {
10316            Slog.wtf(TAG, "Package was null!", new Throwable());
10317            return;
10318        }
10319        clearAppProfilesLeafLIF(pkg);
10320        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10321        for (int i = 0; i < childCount; i++) {
10322            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10323        }
10324    }
10325
10326    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10327        try {
10328            mInstaller.clearAppProfiles(pkg.packageName);
10329        } catch (InstallerException e) {
10330            Slog.w(TAG, String.valueOf(e));
10331        }
10332    }
10333
10334    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10335            long lastUpdateTime) {
10336        // Set parent install/update time
10337        PackageSetting ps = (PackageSetting) pkg.mExtras;
10338        if (ps != null) {
10339            ps.firstInstallTime = firstInstallTime;
10340            ps.lastUpdateTime = lastUpdateTime;
10341        }
10342        // Set children install/update time
10343        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10344        for (int i = 0; i < childCount; i++) {
10345            PackageParser.Package childPkg = pkg.childPackages.get(i);
10346            ps = (PackageSetting) childPkg.mExtras;
10347            if (ps != null) {
10348                ps.firstInstallTime = firstInstallTime;
10349                ps.lastUpdateTime = lastUpdateTime;
10350            }
10351        }
10352    }
10353
10354    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10355            PackageParser.Package changingLib) {
10356        if (file.path != null) {
10357            usesLibraryFiles.add(file.path);
10358            return;
10359        }
10360        PackageParser.Package p = mPackages.get(file.apk);
10361        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10362            // If we are doing this while in the middle of updating a library apk,
10363            // then we need to make sure to use that new apk for determining the
10364            // dependencies here.  (We haven't yet finished committing the new apk
10365            // to the package manager state.)
10366            if (p == null || p.packageName.equals(changingLib.packageName)) {
10367                p = changingLib;
10368            }
10369        }
10370        if (p != null) {
10371            usesLibraryFiles.addAll(p.getAllCodePaths());
10372            if (p.usesLibraryFiles != null) {
10373                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10374            }
10375        }
10376    }
10377
10378    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10379            PackageParser.Package changingLib) throws PackageManagerException {
10380        if (pkg == null) {
10381            return;
10382        }
10383        ArraySet<String> usesLibraryFiles = null;
10384        if (pkg.usesLibraries != null) {
10385            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10386                    null, null, pkg.packageName, changingLib, true,
10387                    pkg.applicationInfo.targetSdkVersion, null);
10388        }
10389        if (pkg.usesStaticLibraries != null) {
10390            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10391                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10392                    pkg.packageName, changingLib, true,
10393                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10394        }
10395        if (pkg.usesOptionalLibraries != null) {
10396            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10397                    null, null, pkg.packageName, changingLib, false,
10398                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10399        }
10400        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10401            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10402        } else {
10403            pkg.usesLibraryFiles = null;
10404        }
10405    }
10406
10407    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10408            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10409            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10410            boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries)
10411            throws PackageManagerException {
10412        final int libCount = requestedLibraries.size();
10413        for (int i = 0; i < libCount; i++) {
10414            final String libName = requestedLibraries.get(i);
10415            final int libVersion = requiredVersions != null ? requiredVersions[i]
10416                    : SharedLibraryInfo.VERSION_UNDEFINED;
10417            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10418            if (libEntry == null) {
10419                if (required) {
10420                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10421                            "Package " + packageName + " requires unavailable shared library "
10422                                    + libName + "; failing!");
10423                } else if (DEBUG_SHARED_LIBRARIES) {
10424                    Slog.i(TAG, "Package " + packageName
10425                            + " desires unavailable shared library "
10426                            + libName + "; ignoring!");
10427                }
10428            } else {
10429                if (requiredVersions != null && requiredCertDigests != null) {
10430                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10431                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10432                            "Package " + packageName + " requires unavailable static shared"
10433                                    + " library " + libName + " version "
10434                                    + libEntry.info.getVersion() + "; failing!");
10435                    }
10436
10437                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10438                    if (libPkg == null) {
10439                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10440                                "Package " + packageName + " requires unavailable static shared"
10441                                        + " library; failing!");
10442                    }
10443
10444                    final String[] expectedCertDigests = requiredCertDigests[i];
10445                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10446                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10447                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10448                            : PackageUtils.computeSignaturesSha256Digests(
10449                                    new Signature[]{libPkg.mSignatures[0]});
10450
10451                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10452                    // target O we don't parse the "additional-certificate" tags similarly
10453                    // how we only consider all certs only for apps targeting O (see above).
10454                    // Therefore, the size check is safe to make.
10455                    if (expectedCertDigests.length != libCertDigests.length) {
10456                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10457                                "Package " + packageName + " requires differently signed" +
10458                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10459                    }
10460
10461                    // Use a predictable order as signature order may vary
10462                    Arrays.sort(libCertDigests);
10463                    Arrays.sort(expectedCertDigests);
10464
10465                    final int certCount = libCertDigests.length;
10466                    for (int j = 0; j < certCount; j++) {
10467                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10468                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10469                                    "Package " + packageName + " requires differently signed" +
10470                                            " static shared library; failing!");
10471                        }
10472                    }
10473                }
10474
10475                if (outUsedLibraries == null) {
10476                    outUsedLibraries = new ArraySet<>();
10477                }
10478                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10479            }
10480        }
10481        return outUsedLibraries;
10482    }
10483
10484    private static boolean hasString(List<String> list, List<String> which) {
10485        if (list == null) {
10486            return false;
10487        }
10488        for (int i=list.size()-1; i>=0; i--) {
10489            for (int j=which.size()-1; j>=0; j--) {
10490                if (which.get(j).equals(list.get(i))) {
10491                    return true;
10492                }
10493            }
10494        }
10495        return false;
10496    }
10497
10498    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10499            PackageParser.Package changingPkg) {
10500        ArrayList<PackageParser.Package> res = null;
10501        for (PackageParser.Package pkg : mPackages.values()) {
10502            if (changingPkg != null
10503                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10504                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10505                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10506                            changingPkg.staticSharedLibName)) {
10507                return null;
10508            }
10509            if (res == null) {
10510                res = new ArrayList<>();
10511            }
10512            res.add(pkg);
10513            try {
10514                updateSharedLibrariesLPr(pkg, changingPkg);
10515            } catch (PackageManagerException e) {
10516                // If a system app update or an app and a required lib missing we
10517                // delete the package and for updated system apps keep the data as
10518                // it is better for the user to reinstall than to be in an limbo
10519                // state. Also libs disappearing under an app should never happen
10520                // - just in case.
10521                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10522                    final int flags = pkg.isUpdatedSystemApp()
10523                            ? PackageManager.DELETE_KEEP_DATA : 0;
10524                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10525                            flags , null, true, null);
10526                }
10527                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10528            }
10529        }
10530        return res;
10531    }
10532
10533    /**
10534     * Derive the value of the {@code cpuAbiOverride} based on the provided
10535     * value and an optional stored value from the package settings.
10536     */
10537    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10538        String cpuAbiOverride = null;
10539
10540        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10541            cpuAbiOverride = null;
10542        } else if (abiOverride != null) {
10543            cpuAbiOverride = abiOverride;
10544        } else if (settings != null) {
10545            cpuAbiOverride = settings.cpuAbiOverrideString;
10546        }
10547
10548        return cpuAbiOverride;
10549    }
10550
10551    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10552            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10553                    throws PackageManagerException {
10554        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10555        // If the package has children and this is the first dive in the function
10556        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10557        // whether all packages (parent and children) would be successfully scanned
10558        // before the actual scan since scanning mutates internal state and we want
10559        // to atomically install the package and its children.
10560        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10561            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10562                scanFlags |= SCAN_CHECK_ONLY;
10563            }
10564        } else {
10565            scanFlags &= ~SCAN_CHECK_ONLY;
10566        }
10567
10568        final PackageParser.Package scannedPkg;
10569        try {
10570            // Scan the parent
10571            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10572            // Scan the children
10573            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10574            for (int i = 0; i < childCount; i++) {
10575                PackageParser.Package childPkg = pkg.childPackages.get(i);
10576                scanPackageLI(childPkg, policyFlags,
10577                        scanFlags, currentTime, user);
10578            }
10579        } finally {
10580            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10581        }
10582
10583        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10584            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10585        }
10586
10587        return scannedPkg;
10588    }
10589
10590    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10591            int scanFlags, long currentTime, @Nullable UserHandle user)
10592                    throws PackageManagerException {
10593        boolean success = false;
10594        try {
10595            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10596                    currentTime, user);
10597            success = true;
10598            return res;
10599        } finally {
10600            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10601                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10602                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10603                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10604                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10605            }
10606        }
10607    }
10608
10609    /**
10610     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10611     */
10612    private static boolean apkHasCode(String fileName) {
10613        StrictJarFile jarFile = null;
10614        try {
10615            jarFile = new StrictJarFile(fileName,
10616                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10617            return jarFile.findEntry("classes.dex") != null;
10618        } catch (IOException ignore) {
10619        } finally {
10620            try {
10621                if (jarFile != null) {
10622                    jarFile.close();
10623                }
10624            } catch (IOException ignore) {}
10625        }
10626        return false;
10627    }
10628
10629    /**
10630     * Enforces code policy for the package. This ensures that if an APK has
10631     * declared hasCode="true" in its manifest that the APK actually contains
10632     * code.
10633     *
10634     * @throws PackageManagerException If bytecode could not be found when it should exist
10635     */
10636    private static void assertCodePolicy(PackageParser.Package pkg)
10637            throws PackageManagerException {
10638        final boolean shouldHaveCode =
10639                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10640        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10641            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10642                    "Package " + pkg.baseCodePath + " code is missing");
10643        }
10644
10645        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10646            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10647                final boolean splitShouldHaveCode =
10648                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10649                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10650                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10651                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10652                }
10653            }
10654        }
10655    }
10656
10657    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10658            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10659                    throws PackageManagerException {
10660        if (DEBUG_PACKAGE_SCANNING) {
10661            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10662                Log.d(TAG, "Scanning package " + pkg.packageName);
10663        }
10664
10665        applyPolicy(pkg, policyFlags);
10666
10667        assertPackageIsValid(pkg, policyFlags, scanFlags);
10668
10669        // Initialize package source and resource directories
10670        final File scanFile = new File(pkg.codePath);
10671        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10672        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10673
10674        SharedUserSetting suid = null;
10675        PackageSetting pkgSetting = null;
10676
10677        // Getting the package setting may have a side-effect, so if we
10678        // are only checking if scan would succeed, stash a copy of the
10679        // old setting to restore at the end.
10680        PackageSetting nonMutatedPs = null;
10681
10682        // We keep references to the derived CPU Abis from settings in oder to reuse
10683        // them in the case where we're not upgrading or booting for the first time.
10684        String primaryCpuAbiFromSettings = null;
10685        String secondaryCpuAbiFromSettings = null;
10686
10687        // writer
10688        synchronized (mPackages) {
10689            if (pkg.mSharedUserId != null) {
10690                // SIDE EFFECTS; may potentially allocate a new shared user
10691                suid = mSettings.getSharedUserLPw(
10692                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10693                if (DEBUG_PACKAGE_SCANNING) {
10694                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10695                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10696                                + "): packages=" + suid.packages);
10697                }
10698            }
10699
10700            // Check if we are renaming from an original package name.
10701            PackageSetting origPackage = null;
10702            String realName = null;
10703            if (pkg.mOriginalPackages != null) {
10704                // This package may need to be renamed to a previously
10705                // installed name.  Let's check on that...
10706                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10707                if (pkg.mOriginalPackages.contains(renamed)) {
10708                    // This package had originally been installed as the
10709                    // original name, and we have already taken care of
10710                    // transitioning to the new one.  Just update the new
10711                    // one to continue using the old name.
10712                    realName = pkg.mRealPackage;
10713                    if (!pkg.packageName.equals(renamed)) {
10714                        // Callers into this function may have already taken
10715                        // care of renaming the package; only do it here if
10716                        // it is not already done.
10717                        pkg.setPackageName(renamed);
10718                    }
10719                } else {
10720                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10721                        if ((origPackage = mSettings.getPackageLPr(
10722                                pkg.mOriginalPackages.get(i))) != null) {
10723                            // We do have the package already installed under its
10724                            // original name...  should we use it?
10725                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10726                                // New package is not compatible with original.
10727                                origPackage = null;
10728                                continue;
10729                            } else if (origPackage.sharedUser != null) {
10730                                // Make sure uid is compatible between packages.
10731                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10732                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10733                                            + " to " + pkg.packageName + ": old uid "
10734                                            + origPackage.sharedUser.name
10735                                            + " differs from " + pkg.mSharedUserId);
10736                                    origPackage = null;
10737                                    continue;
10738                                }
10739                                // TODO: Add case when shared user id is added [b/28144775]
10740                            } else {
10741                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10742                                        + pkg.packageName + " to old name " + origPackage.name);
10743                            }
10744                            break;
10745                        }
10746                    }
10747                }
10748            }
10749
10750            if (mTransferedPackages.contains(pkg.packageName)) {
10751                Slog.w(TAG, "Package " + pkg.packageName
10752                        + " was transferred to another, but its .apk remains");
10753            }
10754
10755            // See comments in nonMutatedPs declaration
10756            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10757                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10758                if (foundPs != null) {
10759                    nonMutatedPs = new PackageSetting(foundPs);
10760                }
10761            }
10762
10763            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10764                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10765                if (foundPs != null) {
10766                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10767                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10768                }
10769            }
10770
10771            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10772            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10773                PackageManagerService.reportSettingsProblem(Log.WARN,
10774                        "Package " + pkg.packageName + " shared user changed from "
10775                                + (pkgSetting.sharedUser != null
10776                                        ? pkgSetting.sharedUser.name : "<nothing>")
10777                                + " to "
10778                                + (suid != null ? suid.name : "<nothing>")
10779                                + "; replacing with new");
10780                pkgSetting = null;
10781            }
10782            final PackageSetting oldPkgSetting =
10783                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10784            final PackageSetting disabledPkgSetting =
10785                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10786
10787            String[] usesStaticLibraries = null;
10788            if (pkg.usesStaticLibraries != null) {
10789                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10790                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10791            }
10792
10793            if (pkgSetting == null) {
10794                final String parentPackageName = (pkg.parentPackage != null)
10795                        ? pkg.parentPackage.packageName : null;
10796                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10797                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10798                // REMOVE SharedUserSetting from method; update in a separate call
10799                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10800                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10801                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10802                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10803                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10804                        true /*allowInstall*/, instantApp, virtualPreload,
10805                        parentPackageName, pkg.getChildPackageNames(),
10806                        UserManagerService.getInstance(), usesStaticLibraries,
10807                        pkg.usesStaticLibrariesVersions);
10808                // SIDE EFFECTS; updates system state; move elsewhere
10809                if (origPackage != null) {
10810                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10811                }
10812                mSettings.addUserToSettingLPw(pkgSetting);
10813            } else {
10814                // REMOVE SharedUserSetting from method; update in a separate call.
10815                //
10816                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10817                // secondaryCpuAbi are not known at this point so we always update them
10818                // to null here, only to reset them at a later point.
10819                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10820                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10821                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10822                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10823                        UserManagerService.getInstance(), usesStaticLibraries,
10824                        pkg.usesStaticLibrariesVersions);
10825            }
10826            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10827            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10828
10829            // SIDE EFFECTS; modifies system state; move elsewhere
10830            if (pkgSetting.origPackage != null) {
10831                // If we are first transitioning from an original package,
10832                // fix up the new package's name now.  We need to do this after
10833                // looking up the package under its new name, so getPackageLP
10834                // can take care of fiddling things correctly.
10835                pkg.setPackageName(origPackage.name);
10836
10837                // File a report about this.
10838                String msg = "New package " + pkgSetting.realName
10839                        + " renamed to replace old package " + pkgSetting.name;
10840                reportSettingsProblem(Log.WARN, msg);
10841
10842                // Make a note of it.
10843                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10844                    mTransferedPackages.add(origPackage.name);
10845                }
10846
10847                // No longer need to retain this.
10848                pkgSetting.origPackage = null;
10849            }
10850
10851            // SIDE EFFECTS; modifies system state; move elsewhere
10852            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10853                // Make a note of it.
10854                mTransferedPackages.add(pkg.packageName);
10855            }
10856
10857            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10858                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10859            }
10860
10861            if ((scanFlags & SCAN_BOOTING) == 0
10862                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10863                // Check all shared libraries and map to their actual file path.
10864                // We only do this here for apps not on a system dir, because those
10865                // are the only ones that can fail an install due to this.  We
10866                // will take care of the system apps by updating all of their
10867                // library paths after the scan is done. Also during the initial
10868                // scan don't update any libs as we do this wholesale after all
10869                // apps are scanned to avoid dependency based scanning.
10870                updateSharedLibrariesLPr(pkg, null);
10871            }
10872
10873            if (mFoundPolicyFile) {
10874                SELinuxMMAC.assignSeInfoValue(pkg);
10875            }
10876            pkg.applicationInfo.uid = pkgSetting.appId;
10877            pkg.mExtras = pkgSetting;
10878
10879
10880            // Static shared libs have same package with different versions where
10881            // we internally use a synthetic package name to allow multiple versions
10882            // of the same package, therefore we need to compare signatures against
10883            // the package setting for the latest library version.
10884            PackageSetting signatureCheckPs = pkgSetting;
10885            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10886                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10887                if (libraryEntry != null) {
10888                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10889                }
10890            }
10891
10892            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10893                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10894                    // We just determined the app is signed correctly, so bring
10895                    // over the latest parsed certs.
10896                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10897                } else {
10898                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10899                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10900                                "Package " + pkg.packageName + " upgrade keys do not match the "
10901                                + "previously installed version");
10902                    } else {
10903                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10904                        String msg = "System package " + pkg.packageName
10905                                + " signature changed; retaining data.";
10906                        reportSettingsProblem(Log.WARN, msg);
10907                    }
10908                }
10909            } else {
10910                try {
10911                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10912                    verifySignaturesLP(signatureCheckPs, pkg);
10913                    // We just determined the app is signed correctly, so bring
10914                    // over the latest parsed certs.
10915                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10916                } catch (PackageManagerException e) {
10917                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10918                        throw e;
10919                    }
10920                    // The signature has changed, but this package is in the system
10921                    // image...  let's recover!
10922                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10923                    // However...  if this package is part of a shared user, but it
10924                    // doesn't match the signature of the shared user, let's fail.
10925                    // What this means is that you can't change the signatures
10926                    // associated with an overall shared user, which doesn't seem all
10927                    // that unreasonable.
10928                    if (signatureCheckPs.sharedUser != null) {
10929                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10930                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10931                            throw new PackageManagerException(
10932                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10933                                    "Signature mismatch for shared user: "
10934                                            + pkgSetting.sharedUser);
10935                        }
10936                    }
10937                    // File a report about this.
10938                    String msg = "System package " + pkg.packageName
10939                            + " signature changed; retaining data.";
10940                    reportSettingsProblem(Log.WARN, msg);
10941                }
10942            }
10943
10944            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10945                // This package wants to adopt ownership of permissions from
10946                // another package.
10947                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10948                    final String origName = pkg.mAdoptPermissions.get(i);
10949                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10950                    if (orig != null) {
10951                        if (verifyPackageUpdateLPr(orig, pkg)) {
10952                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10953                                    + pkg.packageName);
10954                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10955                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10956                        }
10957                    }
10958                }
10959            }
10960        }
10961
10962        pkg.applicationInfo.processName = fixProcessName(
10963                pkg.applicationInfo.packageName,
10964                pkg.applicationInfo.processName);
10965
10966        if (pkg != mPlatformPackage) {
10967            // Get all of our default paths setup
10968            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10969        }
10970
10971        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10972
10973        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10974            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10975                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10976                final boolean extractNativeLibs = !pkg.isLibrary();
10977                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10978                        mAppLib32InstallDir);
10979                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10980
10981                // Some system apps still use directory structure for native libraries
10982                // in which case we might end up not detecting abi solely based on apk
10983                // structure. Try to detect abi based on directory structure.
10984                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10985                        pkg.applicationInfo.primaryCpuAbi == null) {
10986                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10987                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10988                }
10989            } else {
10990                // This is not a first boot or an upgrade, don't bother deriving the
10991                // ABI during the scan. Instead, trust the value that was stored in the
10992                // package setting.
10993                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10994                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10995
10996                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10997
10998                if (DEBUG_ABI_SELECTION) {
10999                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11000                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11001                        pkg.applicationInfo.secondaryCpuAbi);
11002                }
11003            }
11004        } else {
11005            if ((scanFlags & SCAN_MOVE) != 0) {
11006                // We haven't run dex-opt for this move (since we've moved the compiled output too)
11007                // but we already have this packages package info in the PackageSetting. We just
11008                // use that and derive the native library path based on the new codepath.
11009                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11010                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11011            }
11012
11013            // Set native library paths again. For moves, the path will be updated based on the
11014            // ABIs we've determined above. For non-moves, the path will be updated based on the
11015            // ABIs we determined during compilation, but the path will depend on the final
11016            // package path (after the rename away from the stage path).
11017            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11018        }
11019
11020        // This is a special case for the "system" package, where the ABI is
11021        // dictated by the zygote configuration (and init.rc). We should keep track
11022        // of this ABI so that we can deal with "normal" applications that run under
11023        // the same UID correctly.
11024        if (mPlatformPackage == pkg) {
11025            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11026                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11027        }
11028
11029        // If there's a mismatch between the abi-override in the package setting
11030        // and the abiOverride specified for the install. Warn about this because we
11031        // would've already compiled the app without taking the package setting into
11032        // account.
11033        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11034            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11035                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11036                        " for package " + pkg.packageName);
11037            }
11038        }
11039
11040        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11041        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11042        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11043
11044        // Copy the derived override back to the parsed package, so that we can
11045        // update the package settings accordingly.
11046        pkg.cpuAbiOverride = cpuAbiOverride;
11047
11048        if (DEBUG_ABI_SELECTION) {
11049            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11050                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11051                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11052        }
11053
11054        // Push the derived path down into PackageSettings so we know what to
11055        // clean up at uninstall time.
11056        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11057
11058        if (DEBUG_ABI_SELECTION) {
11059            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11060                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11061                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11062        }
11063
11064        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11065        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11066            // We don't do this here during boot because we can do it all
11067            // at once after scanning all existing packages.
11068            //
11069            // We also do this *before* we perform dexopt on this package, so that
11070            // we can avoid redundant dexopts, and also to make sure we've got the
11071            // code and package path correct.
11072            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11073        }
11074
11075        if (mFactoryTest && pkg.requestedPermissions.contains(
11076                android.Manifest.permission.FACTORY_TEST)) {
11077            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11078        }
11079
11080        if (isSystemApp(pkg)) {
11081            pkgSetting.isOrphaned = true;
11082        }
11083
11084        // Take care of first install / last update times.
11085        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11086        if (currentTime != 0) {
11087            if (pkgSetting.firstInstallTime == 0) {
11088                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11089            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11090                pkgSetting.lastUpdateTime = currentTime;
11091            }
11092        } else if (pkgSetting.firstInstallTime == 0) {
11093            // We need *something*.  Take time time stamp of the file.
11094            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11095        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11096            if (scanFileTime != pkgSetting.timeStamp) {
11097                // A package on the system image has changed; consider this
11098                // to be an update.
11099                pkgSetting.lastUpdateTime = scanFileTime;
11100            }
11101        }
11102        pkgSetting.setTimeStamp(scanFileTime);
11103
11104        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11105            if (nonMutatedPs != null) {
11106                synchronized (mPackages) {
11107                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11108                }
11109            }
11110        } else {
11111            final int userId = user == null ? 0 : user.getIdentifier();
11112            // Modify state for the given package setting
11113            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11114                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11115            if (pkgSetting.getInstantApp(userId)) {
11116                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11117            }
11118        }
11119        return pkg;
11120    }
11121
11122    /**
11123     * Applies policy to the parsed package based upon the given policy flags.
11124     * Ensures the package is in a good state.
11125     * <p>
11126     * Implementation detail: This method must NOT have any side effect. It would
11127     * ideally be static, but, it requires locks to read system state.
11128     */
11129    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11130        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11131            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11132            if (pkg.applicationInfo.isDirectBootAware()) {
11133                // we're direct boot aware; set for all components
11134                for (PackageParser.Service s : pkg.services) {
11135                    s.info.encryptionAware = s.info.directBootAware = true;
11136                }
11137                for (PackageParser.Provider p : pkg.providers) {
11138                    p.info.encryptionAware = p.info.directBootAware = true;
11139                }
11140                for (PackageParser.Activity a : pkg.activities) {
11141                    a.info.encryptionAware = a.info.directBootAware = true;
11142                }
11143                for (PackageParser.Activity r : pkg.receivers) {
11144                    r.info.encryptionAware = r.info.directBootAware = true;
11145                }
11146            }
11147            if (compressedFileExists(pkg.codePath)) {
11148                pkg.isStub = true;
11149            }
11150        } else {
11151            // Only allow system apps to be flagged as core apps.
11152            pkg.coreApp = false;
11153            // clear flags not applicable to regular apps
11154            pkg.applicationInfo.privateFlags &=
11155                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11156            pkg.applicationInfo.privateFlags &=
11157                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11158        }
11159        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11160
11161        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11162            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11163        }
11164
11165        if (!isSystemApp(pkg)) {
11166            // Only system apps can use these features.
11167            pkg.mOriginalPackages = null;
11168            pkg.mRealPackage = null;
11169            pkg.mAdoptPermissions = null;
11170        }
11171    }
11172
11173    /**
11174     * Asserts the parsed package is valid according to the given policy. If the
11175     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11176     * <p>
11177     * Implementation detail: This method must NOT have any side effects. It would
11178     * ideally be static, but, it requires locks to read system state.
11179     *
11180     * @throws PackageManagerException If the package fails any of the validation checks
11181     */
11182    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11183            throws PackageManagerException {
11184        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11185            assertCodePolicy(pkg);
11186        }
11187
11188        if (pkg.applicationInfo.getCodePath() == null ||
11189                pkg.applicationInfo.getResourcePath() == null) {
11190            // Bail out. The resource and code paths haven't been set.
11191            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11192                    "Code and resource paths haven't been set correctly");
11193        }
11194
11195        // Make sure we're not adding any bogus keyset info
11196        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11197        ksms.assertScannedPackageValid(pkg);
11198
11199        synchronized (mPackages) {
11200            // The special "android" package can only be defined once
11201            if (pkg.packageName.equals("android")) {
11202                if (mAndroidApplication != null) {
11203                    Slog.w(TAG, "*************************************************");
11204                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11205                    Slog.w(TAG, " codePath=" + pkg.codePath);
11206                    Slog.w(TAG, "*************************************************");
11207                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11208                            "Core android package being redefined.  Skipping.");
11209                }
11210            }
11211
11212            // A package name must be unique; don't allow duplicates
11213            if (mPackages.containsKey(pkg.packageName)) {
11214                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11215                        "Application package " + pkg.packageName
11216                        + " already installed.  Skipping duplicate.");
11217            }
11218
11219            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11220                // Static libs have a synthetic package name containing the version
11221                // but we still want the base name to be unique.
11222                if (mPackages.containsKey(pkg.manifestPackageName)) {
11223                    throw new PackageManagerException(
11224                            "Duplicate static shared lib provider package");
11225                }
11226
11227                // Static shared libraries should have at least O target SDK
11228                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11229                    throw new PackageManagerException(
11230                            "Packages declaring static-shared libs must target O SDK or higher");
11231                }
11232
11233                // Package declaring static a shared lib cannot be instant apps
11234                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11235                    throw new PackageManagerException(
11236                            "Packages declaring static-shared libs cannot be instant apps");
11237                }
11238
11239                // Package declaring static a shared lib cannot be renamed since the package
11240                // name is synthetic and apps can't code around package manager internals.
11241                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11242                    throw new PackageManagerException(
11243                            "Packages declaring static-shared libs cannot be renamed");
11244                }
11245
11246                // Package declaring static a shared lib cannot declare child packages
11247                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11248                    throw new PackageManagerException(
11249                            "Packages declaring static-shared libs cannot have child packages");
11250                }
11251
11252                // Package declaring static a shared lib cannot declare dynamic libs
11253                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11254                    throw new PackageManagerException(
11255                            "Packages declaring static-shared libs cannot declare dynamic libs");
11256                }
11257
11258                // Package declaring static a shared lib cannot declare shared users
11259                if (pkg.mSharedUserId != null) {
11260                    throw new PackageManagerException(
11261                            "Packages declaring static-shared libs cannot declare shared users");
11262                }
11263
11264                // Static shared libs cannot declare activities
11265                if (!pkg.activities.isEmpty()) {
11266                    throw new PackageManagerException(
11267                            "Static shared libs cannot declare activities");
11268                }
11269
11270                // Static shared libs cannot declare services
11271                if (!pkg.services.isEmpty()) {
11272                    throw new PackageManagerException(
11273                            "Static shared libs cannot declare services");
11274                }
11275
11276                // Static shared libs cannot declare providers
11277                if (!pkg.providers.isEmpty()) {
11278                    throw new PackageManagerException(
11279                            "Static shared libs cannot declare content providers");
11280                }
11281
11282                // Static shared libs cannot declare receivers
11283                if (!pkg.receivers.isEmpty()) {
11284                    throw new PackageManagerException(
11285                            "Static shared libs cannot declare broadcast receivers");
11286                }
11287
11288                // Static shared libs cannot declare permission groups
11289                if (!pkg.permissionGroups.isEmpty()) {
11290                    throw new PackageManagerException(
11291                            "Static shared libs cannot declare permission groups");
11292                }
11293
11294                // Static shared libs cannot declare permissions
11295                if (!pkg.permissions.isEmpty()) {
11296                    throw new PackageManagerException(
11297                            "Static shared libs cannot declare permissions");
11298                }
11299
11300                // Static shared libs cannot declare protected broadcasts
11301                if (pkg.protectedBroadcasts != null) {
11302                    throw new PackageManagerException(
11303                            "Static shared libs cannot declare protected broadcasts");
11304                }
11305
11306                // Static shared libs cannot be overlay targets
11307                if (pkg.mOverlayTarget != null) {
11308                    throw new PackageManagerException(
11309                            "Static shared libs cannot be overlay targets");
11310                }
11311
11312                // The version codes must be ordered as lib versions
11313                int minVersionCode = Integer.MIN_VALUE;
11314                int maxVersionCode = Integer.MAX_VALUE;
11315
11316                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11317                        pkg.staticSharedLibName);
11318                if (versionedLib != null) {
11319                    final int versionCount = versionedLib.size();
11320                    for (int i = 0; i < versionCount; i++) {
11321                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11322                        final int libVersionCode = libInfo.getDeclaringPackage()
11323                                .getVersionCode();
11324                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11325                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11326                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11327                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11328                        } else {
11329                            minVersionCode = maxVersionCode = libVersionCode;
11330                            break;
11331                        }
11332                    }
11333                }
11334                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11335                    throw new PackageManagerException("Static shared"
11336                            + " lib version codes must be ordered as lib versions");
11337                }
11338            }
11339
11340            // Only privileged apps and updated privileged apps can add child packages.
11341            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11342                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11343                    throw new PackageManagerException("Only privileged apps can add child "
11344                            + "packages. Ignoring package " + pkg.packageName);
11345                }
11346                final int childCount = pkg.childPackages.size();
11347                for (int i = 0; i < childCount; i++) {
11348                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11349                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11350                            childPkg.packageName)) {
11351                        throw new PackageManagerException("Can't override child of "
11352                                + "another disabled app. Ignoring package " + pkg.packageName);
11353                    }
11354                }
11355            }
11356
11357            // If we're only installing presumed-existing packages, require that the
11358            // scanned APK is both already known and at the path previously established
11359            // for it.  Previously unknown packages we pick up normally, but if we have an
11360            // a priori expectation about this package's install presence, enforce it.
11361            // With a singular exception for new system packages. When an OTA contains
11362            // a new system package, we allow the codepath to change from a system location
11363            // to the user-installed location. If we don't allow this change, any newer,
11364            // user-installed version of the application will be ignored.
11365            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11366                if (mExpectingBetter.containsKey(pkg.packageName)) {
11367                    logCriticalInfo(Log.WARN,
11368                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11369                } else {
11370                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11371                    if (known != null) {
11372                        if (DEBUG_PACKAGE_SCANNING) {
11373                            Log.d(TAG, "Examining " + pkg.codePath
11374                                    + " and requiring known paths " + known.codePathString
11375                                    + " & " + known.resourcePathString);
11376                        }
11377                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11378                                || !pkg.applicationInfo.getResourcePath().equals(
11379                                        known.resourcePathString)) {
11380                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11381                                    "Application package " + pkg.packageName
11382                                    + " found at " + pkg.applicationInfo.getCodePath()
11383                                    + " but expected at " + known.codePathString
11384                                    + "; ignoring.");
11385                        }
11386                    }
11387                }
11388            }
11389
11390            // Verify that this new package doesn't have any content providers
11391            // that conflict with existing packages.  Only do this if the
11392            // package isn't already installed, since we don't want to break
11393            // things that are installed.
11394            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11395                final int N = pkg.providers.size();
11396                int i;
11397                for (i=0; i<N; i++) {
11398                    PackageParser.Provider p = pkg.providers.get(i);
11399                    if (p.info.authority != null) {
11400                        String names[] = p.info.authority.split(";");
11401                        for (int j = 0; j < names.length; j++) {
11402                            if (mProvidersByAuthority.containsKey(names[j])) {
11403                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11404                                final String otherPackageName =
11405                                        ((other != null && other.getComponentName() != null) ?
11406                                                other.getComponentName().getPackageName() : "?");
11407                                throw new PackageManagerException(
11408                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11409                                        "Can't install because provider name " + names[j]
11410                                                + " (in package " + pkg.applicationInfo.packageName
11411                                                + ") is already used by " + otherPackageName);
11412                            }
11413                        }
11414                    }
11415                }
11416            }
11417        }
11418    }
11419
11420    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11421            int type, String declaringPackageName, int declaringVersionCode) {
11422        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11423        if (versionedLib == null) {
11424            versionedLib = new SparseArray<>();
11425            mSharedLibraries.put(name, versionedLib);
11426            if (type == SharedLibraryInfo.TYPE_STATIC) {
11427                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11428            }
11429        } else if (versionedLib.indexOfKey(version) >= 0) {
11430            return false;
11431        }
11432        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11433                version, type, declaringPackageName, declaringVersionCode);
11434        versionedLib.put(version, libEntry);
11435        return true;
11436    }
11437
11438    private boolean removeSharedLibraryLPw(String name, int version) {
11439        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11440        if (versionedLib == null) {
11441            return false;
11442        }
11443        final int libIdx = versionedLib.indexOfKey(version);
11444        if (libIdx < 0) {
11445            return false;
11446        }
11447        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11448        versionedLib.remove(version);
11449        if (versionedLib.size() <= 0) {
11450            mSharedLibraries.remove(name);
11451            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11452                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11453                        .getPackageName());
11454            }
11455        }
11456        return true;
11457    }
11458
11459    /**
11460     * Adds a scanned package to the system. When this method is finished, the package will
11461     * be available for query, resolution, etc...
11462     */
11463    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11464            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11465        final String pkgName = pkg.packageName;
11466        if (mCustomResolverComponentName != null &&
11467                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11468            setUpCustomResolverActivity(pkg);
11469        }
11470
11471        if (pkg.packageName.equals("android")) {
11472            synchronized (mPackages) {
11473                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11474                    // Set up information for our fall-back user intent resolution activity.
11475                    mPlatformPackage = pkg;
11476                    pkg.mVersionCode = mSdkVersion;
11477                    mAndroidApplication = pkg.applicationInfo;
11478                    if (!mResolverReplaced) {
11479                        mResolveActivity.applicationInfo = mAndroidApplication;
11480                        mResolveActivity.name = ResolverActivity.class.getName();
11481                        mResolveActivity.packageName = mAndroidApplication.packageName;
11482                        mResolveActivity.processName = "system:ui";
11483                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11484                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11485                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11486                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11487                        mResolveActivity.exported = true;
11488                        mResolveActivity.enabled = true;
11489                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11490                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11491                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11492                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11493                                | ActivityInfo.CONFIG_ORIENTATION
11494                                | ActivityInfo.CONFIG_KEYBOARD
11495                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11496                        mResolveInfo.activityInfo = mResolveActivity;
11497                        mResolveInfo.priority = 0;
11498                        mResolveInfo.preferredOrder = 0;
11499                        mResolveInfo.match = 0;
11500                        mResolveComponentName = new ComponentName(
11501                                mAndroidApplication.packageName, mResolveActivity.name);
11502                    }
11503                }
11504            }
11505        }
11506
11507        ArrayList<PackageParser.Package> clientLibPkgs = null;
11508        // writer
11509        synchronized (mPackages) {
11510            boolean hasStaticSharedLibs = false;
11511
11512            // Any app can add new static shared libraries
11513            if (pkg.staticSharedLibName != null) {
11514                // Static shared libs don't allow renaming as they have synthetic package
11515                // names to allow install of multiple versions, so use name from manifest.
11516                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11517                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11518                        pkg.manifestPackageName, pkg.mVersionCode)) {
11519                    hasStaticSharedLibs = true;
11520                } else {
11521                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11522                                + pkg.staticSharedLibName + " already exists; skipping");
11523                }
11524                // Static shared libs cannot be updated once installed since they
11525                // use synthetic package name which includes the version code, so
11526                // not need to update other packages's shared lib dependencies.
11527            }
11528
11529            if (!hasStaticSharedLibs
11530                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11531                // Only system apps can add new dynamic shared libraries.
11532                if (pkg.libraryNames != null) {
11533                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11534                        String name = pkg.libraryNames.get(i);
11535                        boolean allowed = false;
11536                        if (pkg.isUpdatedSystemApp()) {
11537                            // New library entries can only be added through the
11538                            // system image.  This is important to get rid of a lot
11539                            // of nasty edge cases: for example if we allowed a non-
11540                            // system update of the app to add a library, then uninstalling
11541                            // the update would make the library go away, and assumptions
11542                            // we made such as through app install filtering would now
11543                            // have allowed apps on the device which aren't compatible
11544                            // with it.  Better to just have the restriction here, be
11545                            // conservative, and create many fewer cases that can negatively
11546                            // impact the user experience.
11547                            final PackageSetting sysPs = mSettings
11548                                    .getDisabledSystemPkgLPr(pkg.packageName);
11549                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11550                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11551                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11552                                        allowed = true;
11553                                        break;
11554                                    }
11555                                }
11556                            }
11557                        } else {
11558                            allowed = true;
11559                        }
11560                        if (allowed) {
11561                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11562                                    SharedLibraryInfo.VERSION_UNDEFINED,
11563                                    SharedLibraryInfo.TYPE_DYNAMIC,
11564                                    pkg.packageName, pkg.mVersionCode)) {
11565                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11566                                        + name + " already exists; skipping");
11567                            }
11568                        } else {
11569                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11570                                    + name + " that is not declared on system image; skipping");
11571                        }
11572                    }
11573
11574                    if ((scanFlags & SCAN_BOOTING) == 0) {
11575                        // If we are not booting, we need to update any applications
11576                        // that are clients of our shared library.  If we are booting,
11577                        // this will all be done once the scan is complete.
11578                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11579                    }
11580                }
11581            }
11582        }
11583
11584        if ((scanFlags & SCAN_BOOTING) != 0) {
11585            // No apps can run during boot scan, so they don't need to be frozen
11586        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11587            // Caller asked to not kill app, so it's probably not frozen
11588        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11589            // Caller asked us to ignore frozen check for some reason; they
11590            // probably didn't know the package name
11591        } else {
11592            // We're doing major surgery on this package, so it better be frozen
11593            // right now to keep it from launching
11594            checkPackageFrozen(pkgName);
11595        }
11596
11597        // Also need to kill any apps that are dependent on the library.
11598        if (clientLibPkgs != null) {
11599            for (int i=0; i<clientLibPkgs.size(); i++) {
11600                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11601                killApplication(clientPkg.applicationInfo.packageName,
11602                        clientPkg.applicationInfo.uid, "update lib");
11603            }
11604        }
11605
11606        // writer
11607        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11608
11609        synchronized (mPackages) {
11610            // We don't expect installation to fail beyond this point
11611
11612            // Add the new setting to mSettings
11613            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11614            // Add the new setting to mPackages
11615            mPackages.put(pkg.applicationInfo.packageName, pkg);
11616            // Make sure we don't accidentally delete its data.
11617            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11618            while (iter.hasNext()) {
11619                PackageCleanItem item = iter.next();
11620                if (pkgName.equals(item.packageName)) {
11621                    iter.remove();
11622                }
11623            }
11624
11625            // Add the package's KeySets to the global KeySetManagerService
11626            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11627            ksms.addScannedPackageLPw(pkg);
11628
11629            int N = pkg.providers.size();
11630            StringBuilder r = null;
11631            int i;
11632            for (i=0; i<N; i++) {
11633                PackageParser.Provider p = pkg.providers.get(i);
11634                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11635                        p.info.processName);
11636                mProviders.addProvider(p);
11637                p.syncable = p.info.isSyncable;
11638                if (p.info.authority != null) {
11639                    String names[] = p.info.authority.split(";");
11640                    p.info.authority = null;
11641                    for (int j = 0; j < names.length; j++) {
11642                        if (j == 1 && p.syncable) {
11643                            // We only want the first authority for a provider to possibly be
11644                            // syncable, so if we already added this provider using a different
11645                            // authority clear the syncable flag. We copy the provider before
11646                            // changing it because the mProviders object contains a reference
11647                            // to a provider that we don't want to change.
11648                            // Only do this for the second authority since the resulting provider
11649                            // object can be the same for all future authorities for this provider.
11650                            p = new PackageParser.Provider(p);
11651                            p.syncable = false;
11652                        }
11653                        if (!mProvidersByAuthority.containsKey(names[j])) {
11654                            mProvidersByAuthority.put(names[j], p);
11655                            if (p.info.authority == null) {
11656                                p.info.authority = names[j];
11657                            } else {
11658                                p.info.authority = p.info.authority + ";" + names[j];
11659                            }
11660                            if (DEBUG_PACKAGE_SCANNING) {
11661                                if (chatty)
11662                                    Log.d(TAG, "Registered content provider: " + names[j]
11663                                            + ", className = " + p.info.name + ", isSyncable = "
11664                                            + p.info.isSyncable);
11665                            }
11666                        } else {
11667                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11668                            Slog.w(TAG, "Skipping provider name " + names[j] +
11669                                    " (in package " + pkg.applicationInfo.packageName +
11670                                    "): name already used by "
11671                                    + ((other != null && other.getComponentName() != null)
11672                                            ? other.getComponentName().getPackageName() : "?"));
11673                        }
11674                    }
11675                }
11676                if (chatty) {
11677                    if (r == null) {
11678                        r = new StringBuilder(256);
11679                    } else {
11680                        r.append(' ');
11681                    }
11682                    r.append(p.info.name);
11683                }
11684            }
11685            if (r != null) {
11686                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11687            }
11688
11689            N = pkg.services.size();
11690            r = null;
11691            for (i=0; i<N; i++) {
11692                PackageParser.Service s = pkg.services.get(i);
11693                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11694                        s.info.processName);
11695                mServices.addService(s);
11696                if (chatty) {
11697                    if (r == null) {
11698                        r = new StringBuilder(256);
11699                    } else {
11700                        r.append(' ');
11701                    }
11702                    r.append(s.info.name);
11703                }
11704            }
11705            if (r != null) {
11706                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11707            }
11708
11709            N = pkg.receivers.size();
11710            r = null;
11711            for (i=0; i<N; i++) {
11712                PackageParser.Activity a = pkg.receivers.get(i);
11713                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11714                        a.info.processName);
11715                mReceivers.addActivity(a, "receiver");
11716                if (chatty) {
11717                    if (r == null) {
11718                        r = new StringBuilder(256);
11719                    } else {
11720                        r.append(' ');
11721                    }
11722                    r.append(a.info.name);
11723                }
11724            }
11725            if (r != null) {
11726                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11727            }
11728
11729            N = pkg.activities.size();
11730            r = null;
11731            for (i=0; i<N; i++) {
11732                PackageParser.Activity a = pkg.activities.get(i);
11733                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11734                        a.info.processName);
11735                mActivities.addActivity(a, "activity");
11736                if (chatty) {
11737                    if (r == null) {
11738                        r = new StringBuilder(256);
11739                    } else {
11740                        r.append(' ');
11741                    }
11742                    r.append(a.info.name);
11743                }
11744            }
11745            if (r != null) {
11746                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11747            }
11748
11749            N = pkg.permissionGroups.size();
11750            r = null;
11751            for (i=0; i<N; i++) {
11752                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11753                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11754                final String curPackageName = cur == null ? null : cur.info.packageName;
11755                // Dont allow ephemeral apps to define new permission groups.
11756                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11757                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11758                            + pg.info.packageName
11759                            + " ignored: instant apps cannot define new permission groups.");
11760                    continue;
11761                }
11762                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11763                if (cur == null || isPackageUpdate) {
11764                    mPermissionGroups.put(pg.info.name, pg);
11765                    if (chatty) {
11766                        if (r == null) {
11767                            r = new StringBuilder(256);
11768                        } else {
11769                            r.append(' ');
11770                        }
11771                        if (isPackageUpdate) {
11772                            r.append("UPD:");
11773                        }
11774                        r.append(pg.info.name);
11775                    }
11776                } else {
11777                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11778                            + pg.info.packageName + " ignored: original from "
11779                            + cur.info.packageName);
11780                    if (chatty) {
11781                        if (r == null) {
11782                            r = new StringBuilder(256);
11783                        } else {
11784                            r.append(' ');
11785                        }
11786                        r.append("DUP:");
11787                        r.append(pg.info.name);
11788                    }
11789                }
11790            }
11791            if (r != null) {
11792                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11793            }
11794
11795            N = pkg.permissions.size();
11796            r = null;
11797            for (i=0; i<N; i++) {
11798                PackageParser.Permission p = pkg.permissions.get(i);
11799
11800                // Dont allow ephemeral apps to define new permissions.
11801                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11802                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11803                            + p.info.packageName
11804                            + " ignored: instant apps cannot define new permissions.");
11805                    continue;
11806                }
11807
11808                // Assume by default that we did not install this permission into the system.
11809                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11810
11811                // Now that permission groups have a special meaning, we ignore permission
11812                // groups for legacy apps to prevent unexpected behavior. In particular,
11813                // permissions for one app being granted to someone just because they happen
11814                // to be in a group defined by another app (before this had no implications).
11815                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11816                    p.group = mPermissionGroups.get(p.info.group);
11817                    // Warn for a permission in an unknown group.
11818                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11819                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11820                                + p.info.packageName + " in an unknown group " + p.info.group);
11821                    }
11822                }
11823
11824                ArrayMap<String, BasePermission> permissionMap =
11825                        p.tree ? mSettings.mPermissionTrees
11826                                : mSettings.mPermissions;
11827                BasePermission bp = permissionMap.get(p.info.name);
11828
11829                // Allow system apps to redefine non-system permissions
11830                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11831                    final boolean currentOwnerIsSystem = (bp.perm != null
11832                            && isSystemApp(bp.perm.owner));
11833                    if (isSystemApp(p.owner)) {
11834                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11835                            // It's a built-in permission and no owner, take ownership now
11836                            bp.packageSetting = pkgSetting;
11837                            bp.perm = p;
11838                            bp.uid = pkg.applicationInfo.uid;
11839                            bp.sourcePackage = p.info.packageName;
11840                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11841                        } else if (!currentOwnerIsSystem) {
11842                            String msg = "New decl " + p.owner + " of permission  "
11843                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11844                            reportSettingsProblem(Log.WARN, msg);
11845                            bp = null;
11846                        }
11847                    }
11848                }
11849
11850                if (bp == null) {
11851                    bp = new BasePermission(p.info.name, p.info.packageName,
11852                            BasePermission.TYPE_NORMAL);
11853                    permissionMap.put(p.info.name, bp);
11854                }
11855
11856                if (bp.perm == null) {
11857                    if (bp.sourcePackage == null
11858                            || bp.sourcePackage.equals(p.info.packageName)) {
11859                        BasePermission tree = findPermissionTreeLP(p.info.name);
11860                        if (tree == null
11861                                || tree.sourcePackage.equals(p.info.packageName)) {
11862                            bp.packageSetting = pkgSetting;
11863                            bp.perm = p;
11864                            bp.uid = pkg.applicationInfo.uid;
11865                            bp.sourcePackage = p.info.packageName;
11866                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11867                            if (chatty) {
11868                                if (r == null) {
11869                                    r = new StringBuilder(256);
11870                                } else {
11871                                    r.append(' ');
11872                                }
11873                                r.append(p.info.name);
11874                            }
11875                        } else {
11876                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11877                                    + p.info.packageName + " ignored: base tree "
11878                                    + tree.name + " is from package "
11879                                    + tree.sourcePackage);
11880                        }
11881                    } else {
11882                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11883                                + p.info.packageName + " ignored: original from "
11884                                + bp.sourcePackage);
11885                    }
11886                } else if (chatty) {
11887                    if (r == null) {
11888                        r = new StringBuilder(256);
11889                    } else {
11890                        r.append(' ');
11891                    }
11892                    r.append("DUP:");
11893                    r.append(p.info.name);
11894                }
11895                if (bp.perm == p) {
11896                    bp.protectionLevel = p.info.protectionLevel;
11897                }
11898            }
11899
11900            if (r != null) {
11901                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11902            }
11903
11904            N = pkg.instrumentation.size();
11905            r = null;
11906            for (i=0; i<N; i++) {
11907                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11908                a.info.packageName = pkg.applicationInfo.packageName;
11909                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11910                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11911                a.info.splitNames = pkg.splitNames;
11912                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11913                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11914                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11915                a.info.dataDir = pkg.applicationInfo.dataDir;
11916                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11917                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11918                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11919                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11920                mInstrumentation.put(a.getComponentName(), a);
11921                if (chatty) {
11922                    if (r == null) {
11923                        r = new StringBuilder(256);
11924                    } else {
11925                        r.append(' ');
11926                    }
11927                    r.append(a.info.name);
11928                }
11929            }
11930            if (r != null) {
11931                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11932            }
11933
11934            if (pkg.protectedBroadcasts != null) {
11935                N = pkg.protectedBroadcasts.size();
11936                synchronized (mProtectedBroadcasts) {
11937                    for (i = 0; i < N; i++) {
11938                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11939                    }
11940                }
11941            }
11942        }
11943
11944        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11945    }
11946
11947    /**
11948     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11949     * is derived purely on the basis of the contents of {@code scanFile} and
11950     * {@code cpuAbiOverride}.
11951     *
11952     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11953     */
11954    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11955                                 String cpuAbiOverride, boolean extractLibs,
11956                                 File appLib32InstallDir)
11957            throws PackageManagerException {
11958        // Give ourselves some initial paths; we'll come back for another
11959        // pass once we've determined ABI below.
11960        setNativeLibraryPaths(pkg, appLib32InstallDir);
11961
11962        // We would never need to extract libs for forward-locked and external packages,
11963        // since the container service will do it for us. We shouldn't attempt to
11964        // extract libs from system app when it was not updated.
11965        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11966                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11967            extractLibs = false;
11968        }
11969
11970        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11971        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11972
11973        NativeLibraryHelper.Handle handle = null;
11974        try {
11975            handle = NativeLibraryHelper.Handle.create(pkg);
11976            // TODO(multiArch): This can be null for apps that didn't go through the
11977            // usual installation process. We can calculate it again, like we
11978            // do during install time.
11979            //
11980            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11981            // unnecessary.
11982            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11983
11984            // Null out the abis so that they can be recalculated.
11985            pkg.applicationInfo.primaryCpuAbi = null;
11986            pkg.applicationInfo.secondaryCpuAbi = null;
11987            if (isMultiArch(pkg.applicationInfo)) {
11988                // Warn if we've set an abiOverride for multi-lib packages..
11989                // By definition, we need to copy both 32 and 64 bit libraries for
11990                // such packages.
11991                if (pkg.cpuAbiOverride != null
11992                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11993                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11994                }
11995
11996                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11997                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11998                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11999                    if (extractLibs) {
12000                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12001                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12002                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12003                                useIsaSpecificSubdirs);
12004                    } else {
12005                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12006                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12007                    }
12008                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12009                }
12010
12011                // Shared library native code should be in the APK zip aligned
12012                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12013                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12014                            "Shared library native lib extraction not supported");
12015                }
12016
12017                maybeThrowExceptionForMultiArchCopy(
12018                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12019
12020                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12021                    if (extractLibs) {
12022                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12023                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12024                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12025                                useIsaSpecificSubdirs);
12026                    } else {
12027                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12028                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12029                    }
12030                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12031                }
12032
12033                maybeThrowExceptionForMultiArchCopy(
12034                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12035
12036                if (abi64 >= 0) {
12037                    // Shared library native libs should be in the APK zip aligned
12038                    if (extractLibs && pkg.isLibrary()) {
12039                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12040                                "Shared library native lib extraction not supported");
12041                    }
12042                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12043                }
12044
12045                if (abi32 >= 0) {
12046                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12047                    if (abi64 >= 0) {
12048                        if (pkg.use32bitAbi) {
12049                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12050                            pkg.applicationInfo.primaryCpuAbi = abi;
12051                        } else {
12052                            pkg.applicationInfo.secondaryCpuAbi = abi;
12053                        }
12054                    } else {
12055                        pkg.applicationInfo.primaryCpuAbi = abi;
12056                    }
12057                }
12058            } else {
12059                String[] abiList = (cpuAbiOverride != null) ?
12060                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12061
12062                // Enable gross and lame hacks for apps that are built with old
12063                // SDK tools. We must scan their APKs for renderscript bitcode and
12064                // not launch them if it's present. Don't bother checking on devices
12065                // that don't have 64 bit support.
12066                boolean needsRenderScriptOverride = false;
12067                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12068                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12069                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12070                    needsRenderScriptOverride = true;
12071                }
12072
12073                final int copyRet;
12074                if (extractLibs) {
12075                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12076                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12077                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12078                } else {
12079                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12080                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12081                }
12082                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12083
12084                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12085                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12086                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12087                }
12088
12089                if (copyRet >= 0) {
12090                    // Shared libraries that have native libs must be multi-architecture
12091                    if (pkg.isLibrary()) {
12092                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12093                                "Shared library with native libs must be multiarch");
12094                    }
12095                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12096                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12097                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12098                } else if (needsRenderScriptOverride) {
12099                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12100                }
12101            }
12102        } catch (IOException ioe) {
12103            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12104        } finally {
12105            IoUtils.closeQuietly(handle);
12106        }
12107
12108        // Now that we've calculated the ABIs and determined if it's an internal app,
12109        // we will go ahead and populate the nativeLibraryPath.
12110        setNativeLibraryPaths(pkg, appLib32InstallDir);
12111    }
12112
12113    /**
12114     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12115     * i.e, so that all packages can be run inside a single process if required.
12116     *
12117     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12118     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12119     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12120     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12121     * updating a package that belongs to a shared user.
12122     *
12123     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12124     * adds unnecessary complexity.
12125     */
12126    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12127            PackageParser.Package scannedPackage) {
12128        String requiredInstructionSet = null;
12129        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12130            requiredInstructionSet = VMRuntime.getInstructionSet(
12131                     scannedPackage.applicationInfo.primaryCpuAbi);
12132        }
12133
12134        PackageSetting requirer = null;
12135        for (PackageSetting ps : packagesForUser) {
12136            // If packagesForUser contains scannedPackage, we skip it. This will happen
12137            // when scannedPackage is an update of an existing package. Without this check,
12138            // we will never be able to change the ABI of any package belonging to a shared
12139            // user, even if it's compatible with other packages.
12140            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12141                if (ps.primaryCpuAbiString == null) {
12142                    continue;
12143                }
12144
12145                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12146                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12147                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12148                    // this but there's not much we can do.
12149                    String errorMessage = "Instruction set mismatch, "
12150                            + ((requirer == null) ? "[caller]" : requirer)
12151                            + " requires " + requiredInstructionSet + " whereas " + ps
12152                            + " requires " + instructionSet;
12153                    Slog.w(TAG, errorMessage);
12154                }
12155
12156                if (requiredInstructionSet == null) {
12157                    requiredInstructionSet = instructionSet;
12158                    requirer = ps;
12159                }
12160            }
12161        }
12162
12163        if (requiredInstructionSet != null) {
12164            String adjustedAbi;
12165            if (requirer != null) {
12166                // requirer != null implies that either scannedPackage was null or that scannedPackage
12167                // did not require an ABI, in which case we have to adjust scannedPackage to match
12168                // the ABI of the set (which is the same as requirer's ABI)
12169                adjustedAbi = requirer.primaryCpuAbiString;
12170                if (scannedPackage != null) {
12171                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12172                }
12173            } else {
12174                // requirer == null implies that we're updating all ABIs in the set to
12175                // match scannedPackage.
12176                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12177            }
12178
12179            for (PackageSetting ps : packagesForUser) {
12180                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12181                    if (ps.primaryCpuAbiString != null) {
12182                        continue;
12183                    }
12184
12185                    ps.primaryCpuAbiString = adjustedAbi;
12186                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12187                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12188                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12189                        if (DEBUG_ABI_SELECTION) {
12190                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12191                                    + " (requirer="
12192                                    + (requirer != null ? requirer.pkg : "null")
12193                                    + ", scannedPackage="
12194                                    + (scannedPackage != null ? scannedPackage : "null")
12195                                    + ")");
12196                        }
12197                        try {
12198                            mInstaller.rmdex(ps.codePathString,
12199                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12200                        } catch (InstallerException ignored) {
12201                        }
12202                    }
12203                }
12204            }
12205        }
12206    }
12207
12208    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12209        synchronized (mPackages) {
12210            mResolverReplaced = true;
12211            // Set up information for custom user intent resolution activity.
12212            mResolveActivity.applicationInfo = pkg.applicationInfo;
12213            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12214            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12215            mResolveActivity.processName = pkg.applicationInfo.packageName;
12216            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12217            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12218                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12219            mResolveActivity.theme = 0;
12220            mResolveActivity.exported = true;
12221            mResolveActivity.enabled = true;
12222            mResolveInfo.activityInfo = mResolveActivity;
12223            mResolveInfo.priority = 0;
12224            mResolveInfo.preferredOrder = 0;
12225            mResolveInfo.match = 0;
12226            mResolveComponentName = mCustomResolverComponentName;
12227            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12228                    mResolveComponentName);
12229        }
12230    }
12231
12232    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12233        if (installerActivity == null) {
12234            if (DEBUG_EPHEMERAL) {
12235                Slog.d(TAG, "Clear ephemeral installer activity");
12236            }
12237            mInstantAppInstallerActivity = null;
12238            return;
12239        }
12240
12241        if (DEBUG_EPHEMERAL) {
12242            Slog.d(TAG, "Set ephemeral installer activity: "
12243                    + installerActivity.getComponentName());
12244        }
12245        // Set up information for ephemeral installer activity
12246        mInstantAppInstallerActivity = installerActivity;
12247        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12248                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12249        mInstantAppInstallerActivity.exported = true;
12250        mInstantAppInstallerActivity.enabled = true;
12251        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12252        mInstantAppInstallerInfo.priority = 0;
12253        mInstantAppInstallerInfo.preferredOrder = 1;
12254        mInstantAppInstallerInfo.isDefault = true;
12255        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12256                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12257    }
12258
12259    private static String calculateBundledApkRoot(final String codePathString) {
12260        final File codePath = new File(codePathString);
12261        final File codeRoot;
12262        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12263            codeRoot = Environment.getRootDirectory();
12264        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12265            codeRoot = Environment.getOemDirectory();
12266        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12267            codeRoot = Environment.getVendorDirectory();
12268        } else {
12269            // Unrecognized code path; take its top real segment as the apk root:
12270            // e.g. /something/app/blah.apk => /something
12271            try {
12272                File f = codePath.getCanonicalFile();
12273                File parent = f.getParentFile();    // non-null because codePath is a file
12274                File tmp;
12275                while ((tmp = parent.getParentFile()) != null) {
12276                    f = parent;
12277                    parent = tmp;
12278                }
12279                codeRoot = f;
12280                Slog.w(TAG, "Unrecognized code path "
12281                        + codePath + " - using " + codeRoot);
12282            } catch (IOException e) {
12283                // Can't canonicalize the code path -- shenanigans?
12284                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12285                return Environment.getRootDirectory().getPath();
12286            }
12287        }
12288        return codeRoot.getPath();
12289    }
12290
12291    /**
12292     * Derive and set the location of native libraries for the given package,
12293     * which varies depending on where and how the package was installed.
12294     */
12295    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12296        final ApplicationInfo info = pkg.applicationInfo;
12297        final String codePath = pkg.codePath;
12298        final File codeFile = new File(codePath);
12299        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12300        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12301
12302        info.nativeLibraryRootDir = null;
12303        info.nativeLibraryRootRequiresIsa = false;
12304        info.nativeLibraryDir = null;
12305        info.secondaryNativeLibraryDir = null;
12306
12307        if (isApkFile(codeFile)) {
12308            // Monolithic install
12309            if (bundledApp) {
12310                // If "/system/lib64/apkname" exists, assume that is the per-package
12311                // native library directory to use; otherwise use "/system/lib/apkname".
12312                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12313                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12314                        getPrimaryInstructionSet(info));
12315
12316                // This is a bundled system app so choose the path based on the ABI.
12317                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12318                // is just the default path.
12319                final String apkName = deriveCodePathName(codePath);
12320                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12321                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12322                        apkName).getAbsolutePath();
12323
12324                if (info.secondaryCpuAbi != null) {
12325                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12326                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12327                            secondaryLibDir, apkName).getAbsolutePath();
12328                }
12329            } else if (asecApp) {
12330                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12331                        .getAbsolutePath();
12332            } else {
12333                final String apkName = deriveCodePathName(codePath);
12334                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12335                        .getAbsolutePath();
12336            }
12337
12338            info.nativeLibraryRootRequiresIsa = false;
12339            info.nativeLibraryDir = info.nativeLibraryRootDir;
12340        } else {
12341            // Cluster install
12342            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12343            info.nativeLibraryRootRequiresIsa = true;
12344
12345            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12346                    getPrimaryInstructionSet(info)).getAbsolutePath();
12347
12348            if (info.secondaryCpuAbi != null) {
12349                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12350                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12351            }
12352        }
12353    }
12354
12355    /**
12356     * Calculate the abis and roots for a bundled app. These can uniquely
12357     * be determined from the contents of the system partition, i.e whether
12358     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12359     * of this information, and instead assume that the system was built
12360     * sensibly.
12361     */
12362    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12363                                           PackageSetting pkgSetting) {
12364        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12365
12366        // If "/system/lib64/apkname" exists, assume that is the per-package
12367        // native library directory to use; otherwise use "/system/lib/apkname".
12368        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12369        setBundledAppAbi(pkg, apkRoot, apkName);
12370        // pkgSetting might be null during rescan following uninstall of updates
12371        // to a bundled app, so accommodate that possibility.  The settings in
12372        // that case will be established later from the parsed package.
12373        //
12374        // If the settings aren't null, sync them up with what we've just derived.
12375        // note that apkRoot isn't stored in the package settings.
12376        if (pkgSetting != null) {
12377            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12378            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12379        }
12380    }
12381
12382    /**
12383     * Deduces the ABI of a bundled app and sets the relevant fields on the
12384     * parsed pkg object.
12385     *
12386     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12387     *        under which system libraries are installed.
12388     * @param apkName the name of the installed package.
12389     */
12390    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12391        final File codeFile = new File(pkg.codePath);
12392
12393        final boolean has64BitLibs;
12394        final boolean has32BitLibs;
12395        if (isApkFile(codeFile)) {
12396            // Monolithic install
12397            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12398            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12399        } else {
12400            // Cluster install
12401            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12402            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12403                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12404                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12405                has64BitLibs = (new File(rootDir, isa)).exists();
12406            } else {
12407                has64BitLibs = false;
12408            }
12409            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12410                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12411                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12412                has32BitLibs = (new File(rootDir, isa)).exists();
12413            } else {
12414                has32BitLibs = false;
12415            }
12416        }
12417
12418        if (has64BitLibs && !has32BitLibs) {
12419            // The package has 64 bit libs, but not 32 bit libs. Its primary
12420            // ABI should be 64 bit. We can safely assume here that the bundled
12421            // native libraries correspond to the most preferred ABI in the list.
12422
12423            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12424            pkg.applicationInfo.secondaryCpuAbi = null;
12425        } else if (has32BitLibs && !has64BitLibs) {
12426            // The package has 32 bit libs but not 64 bit libs. Its primary
12427            // ABI should be 32 bit.
12428
12429            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12430            pkg.applicationInfo.secondaryCpuAbi = null;
12431        } else if (has32BitLibs && has64BitLibs) {
12432            // The application has both 64 and 32 bit bundled libraries. We check
12433            // here that the app declares multiArch support, and warn if it doesn't.
12434            //
12435            // We will be lenient here and record both ABIs. The primary will be the
12436            // ABI that's higher on the list, i.e, a device that's configured to prefer
12437            // 64 bit apps will see a 64 bit primary ABI,
12438
12439            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12440                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12441            }
12442
12443            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12444                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12445                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12446            } else {
12447                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12448                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12449            }
12450        } else {
12451            pkg.applicationInfo.primaryCpuAbi = null;
12452            pkg.applicationInfo.secondaryCpuAbi = null;
12453        }
12454    }
12455
12456    private void killApplication(String pkgName, int appId, String reason) {
12457        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12458    }
12459
12460    private void killApplication(String pkgName, int appId, int userId, String reason) {
12461        // Request the ActivityManager to kill the process(only for existing packages)
12462        // so that we do not end up in a confused state while the user is still using the older
12463        // version of the application while the new one gets installed.
12464        final long token = Binder.clearCallingIdentity();
12465        try {
12466            IActivityManager am = ActivityManager.getService();
12467            if (am != null) {
12468                try {
12469                    am.killApplication(pkgName, appId, userId, reason);
12470                } catch (RemoteException e) {
12471                }
12472            }
12473        } finally {
12474            Binder.restoreCallingIdentity(token);
12475        }
12476    }
12477
12478    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12479        // Remove the parent package setting
12480        PackageSetting ps = (PackageSetting) pkg.mExtras;
12481        if (ps != null) {
12482            removePackageLI(ps, chatty);
12483        }
12484        // Remove the child package setting
12485        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12486        for (int i = 0; i < childCount; i++) {
12487            PackageParser.Package childPkg = pkg.childPackages.get(i);
12488            ps = (PackageSetting) childPkg.mExtras;
12489            if (ps != null) {
12490                removePackageLI(ps, chatty);
12491            }
12492        }
12493    }
12494
12495    void removePackageLI(PackageSetting ps, boolean chatty) {
12496        if (DEBUG_INSTALL) {
12497            if (chatty)
12498                Log.d(TAG, "Removing package " + ps.name);
12499        }
12500
12501        // writer
12502        synchronized (mPackages) {
12503            mPackages.remove(ps.name);
12504            final PackageParser.Package pkg = ps.pkg;
12505            if (pkg != null) {
12506                cleanPackageDataStructuresLILPw(pkg, chatty);
12507            }
12508        }
12509    }
12510
12511    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12512        if (DEBUG_INSTALL) {
12513            if (chatty)
12514                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12515        }
12516
12517        // writer
12518        synchronized (mPackages) {
12519            // Remove the parent package
12520            mPackages.remove(pkg.applicationInfo.packageName);
12521            cleanPackageDataStructuresLILPw(pkg, chatty);
12522
12523            // Remove the child packages
12524            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12525            for (int i = 0; i < childCount; i++) {
12526                PackageParser.Package childPkg = pkg.childPackages.get(i);
12527                mPackages.remove(childPkg.applicationInfo.packageName);
12528                cleanPackageDataStructuresLILPw(childPkg, chatty);
12529            }
12530        }
12531    }
12532
12533    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12534        int N = pkg.providers.size();
12535        StringBuilder r = null;
12536        int i;
12537        for (i=0; i<N; i++) {
12538            PackageParser.Provider p = pkg.providers.get(i);
12539            mProviders.removeProvider(p);
12540            if (p.info.authority == null) {
12541
12542                /* There was another ContentProvider with this authority when
12543                 * this app was installed so this authority is null,
12544                 * Ignore it as we don't have to unregister the provider.
12545                 */
12546                continue;
12547            }
12548            String names[] = p.info.authority.split(";");
12549            for (int j = 0; j < names.length; j++) {
12550                if (mProvidersByAuthority.get(names[j]) == p) {
12551                    mProvidersByAuthority.remove(names[j]);
12552                    if (DEBUG_REMOVE) {
12553                        if (chatty)
12554                            Log.d(TAG, "Unregistered content provider: " + names[j]
12555                                    + ", className = " + p.info.name + ", isSyncable = "
12556                                    + p.info.isSyncable);
12557                    }
12558                }
12559            }
12560            if (DEBUG_REMOVE && chatty) {
12561                if (r == null) {
12562                    r = new StringBuilder(256);
12563                } else {
12564                    r.append(' ');
12565                }
12566                r.append(p.info.name);
12567            }
12568        }
12569        if (r != null) {
12570            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12571        }
12572
12573        N = pkg.services.size();
12574        r = null;
12575        for (i=0; i<N; i++) {
12576            PackageParser.Service s = pkg.services.get(i);
12577            mServices.removeService(s);
12578            if (chatty) {
12579                if (r == null) {
12580                    r = new StringBuilder(256);
12581                } else {
12582                    r.append(' ');
12583                }
12584                r.append(s.info.name);
12585            }
12586        }
12587        if (r != null) {
12588            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12589        }
12590
12591        N = pkg.receivers.size();
12592        r = null;
12593        for (i=0; i<N; i++) {
12594            PackageParser.Activity a = pkg.receivers.get(i);
12595            mReceivers.removeActivity(a, "receiver");
12596            if (DEBUG_REMOVE && chatty) {
12597                if (r == null) {
12598                    r = new StringBuilder(256);
12599                } else {
12600                    r.append(' ');
12601                }
12602                r.append(a.info.name);
12603            }
12604        }
12605        if (r != null) {
12606            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12607        }
12608
12609        N = pkg.activities.size();
12610        r = null;
12611        for (i=0; i<N; i++) {
12612            PackageParser.Activity a = pkg.activities.get(i);
12613            mActivities.removeActivity(a, "activity");
12614            if (DEBUG_REMOVE && chatty) {
12615                if (r == null) {
12616                    r = new StringBuilder(256);
12617                } else {
12618                    r.append(' ');
12619                }
12620                r.append(a.info.name);
12621            }
12622        }
12623        if (r != null) {
12624            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12625        }
12626
12627        N = pkg.permissions.size();
12628        r = null;
12629        for (i=0; i<N; i++) {
12630            PackageParser.Permission p = pkg.permissions.get(i);
12631            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12632            if (bp == null) {
12633                bp = mSettings.mPermissionTrees.get(p.info.name);
12634            }
12635            if (bp != null && bp.perm == p) {
12636                bp.perm = null;
12637                if (DEBUG_REMOVE && chatty) {
12638                    if (r == null) {
12639                        r = new StringBuilder(256);
12640                    } else {
12641                        r.append(' ');
12642                    }
12643                    r.append(p.info.name);
12644                }
12645            }
12646            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12647                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12648                if (appOpPkgs != null) {
12649                    appOpPkgs.remove(pkg.packageName);
12650                }
12651            }
12652        }
12653        if (r != null) {
12654            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12655        }
12656
12657        N = pkg.requestedPermissions.size();
12658        r = null;
12659        for (i=0; i<N; i++) {
12660            String perm = pkg.requestedPermissions.get(i);
12661            BasePermission bp = mSettings.mPermissions.get(perm);
12662            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12663                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12664                if (appOpPkgs != null) {
12665                    appOpPkgs.remove(pkg.packageName);
12666                    if (appOpPkgs.isEmpty()) {
12667                        mAppOpPermissionPackages.remove(perm);
12668                    }
12669                }
12670            }
12671        }
12672        if (r != null) {
12673            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12674        }
12675
12676        N = pkg.instrumentation.size();
12677        r = null;
12678        for (i=0; i<N; i++) {
12679            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12680            mInstrumentation.remove(a.getComponentName());
12681            if (DEBUG_REMOVE && chatty) {
12682                if (r == null) {
12683                    r = new StringBuilder(256);
12684                } else {
12685                    r.append(' ');
12686                }
12687                r.append(a.info.name);
12688            }
12689        }
12690        if (r != null) {
12691            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12692        }
12693
12694        r = null;
12695        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12696            // Only system apps can hold shared libraries.
12697            if (pkg.libraryNames != null) {
12698                for (i = 0; i < pkg.libraryNames.size(); i++) {
12699                    String name = pkg.libraryNames.get(i);
12700                    if (removeSharedLibraryLPw(name, 0)) {
12701                        if (DEBUG_REMOVE && chatty) {
12702                            if (r == null) {
12703                                r = new StringBuilder(256);
12704                            } else {
12705                                r.append(' ');
12706                            }
12707                            r.append(name);
12708                        }
12709                    }
12710                }
12711            }
12712        }
12713
12714        r = null;
12715
12716        // Any package can hold static shared libraries.
12717        if (pkg.staticSharedLibName != null) {
12718            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12719                if (DEBUG_REMOVE && chatty) {
12720                    if (r == null) {
12721                        r = new StringBuilder(256);
12722                    } else {
12723                        r.append(' ');
12724                    }
12725                    r.append(pkg.staticSharedLibName);
12726                }
12727            }
12728        }
12729
12730        if (r != null) {
12731            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12732        }
12733    }
12734
12735    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12736        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12737            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12738                return true;
12739            }
12740        }
12741        return false;
12742    }
12743
12744    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12745    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12746    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12747
12748    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12749        // Update the parent permissions
12750        updatePermissionsLPw(pkg.packageName, pkg, flags);
12751        // Update the child permissions
12752        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12753        for (int i = 0; i < childCount; i++) {
12754            PackageParser.Package childPkg = pkg.childPackages.get(i);
12755            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12756        }
12757    }
12758
12759    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12760            int flags) {
12761        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12762        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12763    }
12764
12765    private void updatePermissionsLPw(String changingPkg,
12766            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12767        // Make sure there are no dangling permission trees.
12768        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12769        while (it.hasNext()) {
12770            final BasePermission bp = it.next();
12771            if (bp.packageSetting == null) {
12772                // We may not yet have parsed the package, so just see if
12773                // we still know about its settings.
12774                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12775            }
12776            if (bp.packageSetting == null) {
12777                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12778                        + " from package " + bp.sourcePackage);
12779                it.remove();
12780            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12781                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12782                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12783                            + " from package " + bp.sourcePackage);
12784                    flags |= UPDATE_PERMISSIONS_ALL;
12785                    it.remove();
12786                }
12787            }
12788        }
12789
12790        // Make sure all dynamic permissions have been assigned to a package,
12791        // and make sure there are no dangling permissions.
12792        it = mSettings.mPermissions.values().iterator();
12793        while (it.hasNext()) {
12794            final BasePermission bp = it.next();
12795            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12796                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12797                        + bp.name + " pkg=" + bp.sourcePackage
12798                        + " info=" + bp.pendingInfo);
12799                if (bp.packageSetting == null && bp.pendingInfo != null) {
12800                    final BasePermission tree = findPermissionTreeLP(bp.name);
12801                    if (tree != null && tree.perm != null) {
12802                        bp.packageSetting = tree.packageSetting;
12803                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12804                                new PermissionInfo(bp.pendingInfo));
12805                        bp.perm.info.packageName = tree.perm.info.packageName;
12806                        bp.perm.info.name = bp.name;
12807                        bp.uid = tree.uid;
12808                    }
12809                }
12810            }
12811            if (bp.packageSetting == null) {
12812                // We may not yet have parsed the package, so just see if
12813                // we still know about its settings.
12814                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12815            }
12816            if (bp.packageSetting == null) {
12817                Slog.w(TAG, "Removing dangling permission: " + bp.name
12818                        + " from package " + bp.sourcePackage);
12819                it.remove();
12820            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12821                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12822                    Slog.i(TAG, "Removing old permission: " + bp.name
12823                            + " from package " + bp.sourcePackage);
12824                    flags |= UPDATE_PERMISSIONS_ALL;
12825                    it.remove();
12826                }
12827            }
12828        }
12829
12830        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12831        // Now update the permissions for all packages, in particular
12832        // replace the granted permissions of the system packages.
12833        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12834            for (PackageParser.Package pkg : mPackages.values()) {
12835                if (pkg != pkgInfo) {
12836                    // Only replace for packages on requested volume
12837                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12838                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12839                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12840                    grantPermissionsLPw(pkg, replace, changingPkg);
12841                }
12842            }
12843        }
12844
12845        if (pkgInfo != null) {
12846            // Only replace for packages on requested volume
12847            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12848            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12849                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12850            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12851        }
12852        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12853    }
12854
12855    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12856            String packageOfInterest) {
12857        // IMPORTANT: There are two types of permissions: install and runtime.
12858        // Install time permissions are granted when the app is installed to
12859        // all device users and users added in the future. Runtime permissions
12860        // are granted at runtime explicitly to specific users. Normal and signature
12861        // protected permissions are install time permissions. Dangerous permissions
12862        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12863        // otherwise they are runtime permissions. This function does not manage
12864        // runtime permissions except for the case an app targeting Lollipop MR1
12865        // being upgraded to target a newer SDK, in which case dangerous permissions
12866        // are transformed from install time to runtime ones.
12867
12868        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12869        if (ps == null) {
12870            return;
12871        }
12872
12873        PermissionsState permissionsState = ps.getPermissionsState();
12874        PermissionsState origPermissions = permissionsState;
12875
12876        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12877
12878        boolean runtimePermissionsRevoked = false;
12879        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12880
12881        boolean changedInstallPermission = false;
12882
12883        if (replace) {
12884            ps.installPermissionsFixed = false;
12885            if (!ps.isSharedUser()) {
12886                origPermissions = new PermissionsState(permissionsState);
12887                permissionsState.reset();
12888            } else {
12889                // We need to know only about runtime permission changes since the
12890                // calling code always writes the install permissions state but
12891                // the runtime ones are written only if changed. The only cases of
12892                // changed runtime permissions here are promotion of an install to
12893                // runtime and revocation of a runtime from a shared user.
12894                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12895                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12896                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12897                    runtimePermissionsRevoked = true;
12898                }
12899            }
12900        }
12901
12902        permissionsState.setGlobalGids(mGlobalGids);
12903
12904        final int N = pkg.requestedPermissions.size();
12905        for (int i=0; i<N; i++) {
12906            final String name = pkg.requestedPermissions.get(i);
12907            final BasePermission bp = mSettings.mPermissions.get(name);
12908            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12909                    >= Build.VERSION_CODES.M;
12910
12911            if (DEBUG_INSTALL) {
12912                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12913            }
12914
12915            if (bp == null || bp.packageSetting == null) {
12916                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12917                    if (DEBUG_PERMISSIONS) {
12918                        Slog.i(TAG, "Unknown permission " + name
12919                                + " in package " + pkg.packageName);
12920                    }
12921                }
12922                continue;
12923            }
12924
12925
12926            // Limit ephemeral apps to ephemeral allowed permissions.
12927            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12928                if (DEBUG_PERMISSIONS) {
12929                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12930                            + pkg.packageName);
12931                }
12932                continue;
12933            }
12934
12935            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12936                if (DEBUG_PERMISSIONS) {
12937                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12938                            + pkg.packageName);
12939                }
12940                continue;
12941            }
12942
12943            final String perm = bp.name;
12944            boolean allowedSig = false;
12945            int grant = GRANT_DENIED;
12946
12947            // Keep track of app op permissions.
12948            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12949                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12950                if (pkgs == null) {
12951                    pkgs = new ArraySet<>();
12952                    mAppOpPermissionPackages.put(bp.name, pkgs);
12953                }
12954                pkgs.add(pkg.packageName);
12955            }
12956
12957            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12958            switch (level) {
12959                case PermissionInfo.PROTECTION_NORMAL: {
12960                    // For all apps normal permissions are install time ones.
12961                    grant = GRANT_INSTALL;
12962                } break;
12963
12964                case PermissionInfo.PROTECTION_DANGEROUS: {
12965                    // If a permission review is required for legacy apps we represent
12966                    // their permissions as always granted runtime ones since we need
12967                    // to keep the review required permission flag per user while an
12968                    // install permission's state is shared across all users.
12969                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12970                        // For legacy apps dangerous permissions are install time ones.
12971                        grant = GRANT_INSTALL;
12972                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12973                        // For legacy apps that became modern, install becomes runtime.
12974                        grant = GRANT_UPGRADE;
12975                    } else if (mPromoteSystemApps
12976                            && isSystemApp(ps)
12977                            && mExistingSystemPackages.contains(ps.name)) {
12978                        // For legacy system apps, install becomes runtime.
12979                        // We cannot check hasInstallPermission() for system apps since those
12980                        // permissions were granted implicitly and not persisted pre-M.
12981                        grant = GRANT_UPGRADE;
12982                    } else {
12983                        // For modern apps keep runtime permissions unchanged.
12984                        grant = GRANT_RUNTIME;
12985                    }
12986                } break;
12987
12988                case PermissionInfo.PROTECTION_SIGNATURE: {
12989                    // For all apps signature permissions are install time ones.
12990                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12991                    if (allowedSig) {
12992                        grant = GRANT_INSTALL;
12993                    }
12994                } break;
12995            }
12996
12997            if (DEBUG_PERMISSIONS) {
12998                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12999            }
13000
13001            if (grant != GRANT_DENIED) {
13002                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
13003                    // If this is an existing, non-system package, then
13004                    // we can't add any new permissions to it.
13005                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
13006                        // Except...  if this is a permission that was added
13007                        // to the platform (note: need to only do this when
13008                        // updating the platform).
13009                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
13010                            grant = GRANT_DENIED;
13011                        }
13012                    }
13013                }
13014
13015                switch (grant) {
13016                    case GRANT_INSTALL: {
13017                        // Revoke this as runtime permission to handle the case of
13018                        // a runtime permission being downgraded to an install one.
13019                        // Also in permission review mode we keep dangerous permissions
13020                        // for legacy apps
13021                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13022                            if (origPermissions.getRuntimePermissionState(
13023                                    bp.name, userId) != null) {
13024                                // Revoke the runtime permission and clear the flags.
13025                                origPermissions.revokeRuntimePermission(bp, userId);
13026                                origPermissions.updatePermissionFlags(bp, userId,
13027                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
13028                                // If we revoked a permission permission, we have to write.
13029                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13030                                        changedRuntimePermissionUserIds, userId);
13031                            }
13032                        }
13033                        // Grant an install permission.
13034                        if (permissionsState.grantInstallPermission(bp) !=
13035                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13036                            changedInstallPermission = true;
13037                        }
13038                    } break;
13039
13040                    case GRANT_RUNTIME: {
13041                        // Grant previously granted runtime permissions.
13042                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13043                            PermissionState permissionState = origPermissions
13044                                    .getRuntimePermissionState(bp.name, userId);
13045                            int flags = permissionState != null
13046                                    ? permissionState.getFlags() : 0;
13047                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13048                                // Don't propagate the permission in a permission review mode if
13049                                // the former was revoked, i.e. marked to not propagate on upgrade.
13050                                // Note that in a permission review mode install permissions are
13051                                // represented as constantly granted runtime ones since we need to
13052                                // keep a per user state associated with the permission. Also the
13053                                // revoke on upgrade flag is no longer applicable and is reset.
13054                                final boolean revokeOnUpgrade = (flags & PackageManager
13055                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13056                                if (revokeOnUpgrade) {
13057                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13058                                    // Since we changed the flags, we have to write.
13059                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13060                                            changedRuntimePermissionUserIds, userId);
13061                                }
13062                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13063                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13064                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13065                                        // If we cannot put the permission as it was,
13066                                        // we have to write.
13067                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13068                                                changedRuntimePermissionUserIds, userId);
13069                                    }
13070                                }
13071
13072                                // If the app supports runtime permissions no need for a review.
13073                                if (mPermissionReviewRequired
13074                                        && appSupportsRuntimePermissions
13075                                        && (flags & PackageManager
13076                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13077                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13078                                    // Since we changed the flags, we have to write.
13079                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13080                                            changedRuntimePermissionUserIds, userId);
13081                                }
13082                            } else if (mPermissionReviewRequired
13083                                    && !appSupportsRuntimePermissions) {
13084                                // For legacy apps that need a permission review, every new
13085                                // runtime permission is granted but it is pending a review.
13086                                // We also need to review only platform defined runtime
13087                                // permissions as these are the only ones the platform knows
13088                                // how to disable the API to simulate revocation as legacy
13089                                // apps don't expect to run with revoked permissions.
13090                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13091                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13092                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13093                                        // We changed the flags, hence have to write.
13094                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13095                                                changedRuntimePermissionUserIds, userId);
13096                                    }
13097                                }
13098                                if (permissionsState.grantRuntimePermission(bp, userId)
13099                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13100                                    // We changed the permission, hence have to write.
13101                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13102                                            changedRuntimePermissionUserIds, userId);
13103                                }
13104                            }
13105                            // Propagate the permission flags.
13106                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13107                        }
13108                    } break;
13109
13110                    case GRANT_UPGRADE: {
13111                        // Grant runtime permissions for a previously held install permission.
13112                        PermissionState permissionState = origPermissions
13113                                .getInstallPermissionState(bp.name);
13114                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13115
13116                        if (origPermissions.revokeInstallPermission(bp)
13117                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13118                            // We will be transferring the permission flags, so clear them.
13119                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13120                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13121                            changedInstallPermission = true;
13122                        }
13123
13124                        // If the permission is not to be promoted to runtime we ignore it and
13125                        // also its other flags as they are not applicable to install permissions.
13126                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13127                            for (int userId : currentUserIds) {
13128                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13129                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13130                                    // Transfer the permission flags.
13131                                    permissionsState.updatePermissionFlags(bp, userId,
13132                                            flags, flags);
13133                                    // If we granted the permission, we have to write.
13134                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13135                                            changedRuntimePermissionUserIds, userId);
13136                                }
13137                            }
13138                        }
13139                    } break;
13140
13141                    default: {
13142                        if (packageOfInterest == null
13143                                || packageOfInterest.equals(pkg.packageName)) {
13144                            if (DEBUG_PERMISSIONS) {
13145                                Slog.i(TAG, "Not granting permission " + perm
13146                                        + " to package " + pkg.packageName
13147                                        + " because it was previously installed without");
13148                            }
13149                        }
13150                    } break;
13151                }
13152            } else {
13153                if (permissionsState.revokeInstallPermission(bp) !=
13154                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13155                    // Also drop the permission flags.
13156                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13157                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13158                    changedInstallPermission = true;
13159                    Slog.i(TAG, "Un-granting permission " + perm
13160                            + " from package " + pkg.packageName
13161                            + " (protectionLevel=" + bp.protectionLevel
13162                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13163                            + ")");
13164                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13165                    // Don't print warning for app op permissions, since it is fine for them
13166                    // not to be granted, there is a UI for the user to decide.
13167                    if (DEBUG_PERMISSIONS
13168                            && (packageOfInterest == null
13169                                    || packageOfInterest.equals(pkg.packageName))) {
13170                        Slog.i(TAG, "Not granting permission " + perm
13171                                + " to package " + pkg.packageName
13172                                + " (protectionLevel=" + bp.protectionLevel
13173                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13174                                + ")");
13175                    }
13176                }
13177            }
13178        }
13179
13180        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13181                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13182            // This is the first that we have heard about this package, so the
13183            // permissions we have now selected are fixed until explicitly
13184            // changed.
13185            ps.installPermissionsFixed = true;
13186        }
13187
13188        // Persist the runtime permissions state for users with changes. If permissions
13189        // were revoked because no app in the shared user declares them we have to
13190        // write synchronously to avoid losing runtime permissions state.
13191        for (int userId : changedRuntimePermissionUserIds) {
13192            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13193        }
13194    }
13195
13196    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13197        boolean allowed = false;
13198        final int NP = PackageParser.NEW_PERMISSIONS.length;
13199        for (int ip=0; ip<NP; ip++) {
13200            final PackageParser.NewPermissionInfo npi
13201                    = PackageParser.NEW_PERMISSIONS[ip];
13202            if (npi.name.equals(perm)
13203                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13204                allowed = true;
13205                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13206                        + pkg.packageName);
13207                break;
13208            }
13209        }
13210        return allowed;
13211    }
13212
13213    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13214            BasePermission bp, PermissionsState origPermissions) {
13215        boolean privilegedPermission = (bp.protectionLevel
13216                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13217        boolean privappPermissionsDisable =
13218                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13219        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13220        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13221        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13222                && !platformPackage && platformPermission) {
13223            final ArraySet<String> allowedPermissions = SystemConfig.getInstance()
13224                    .getPrivAppPermissions(pkg.packageName);
13225            final boolean whitelisted =
13226                    allowedPermissions != null && allowedPermissions.contains(perm);
13227            if (!whitelisted) {
13228                Slog.w(TAG, "Privileged permission " + perm + " for package "
13229                        + pkg.packageName + " - not in privapp-permissions whitelist");
13230                // Only report violations for apps on system image
13231                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13232                    // it's only a reportable violation if the permission isn't explicitly denied
13233                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13234                            .getPrivAppDenyPermissions(pkg.packageName);
13235                    final boolean permissionViolation =
13236                            deniedPermissions == null || !deniedPermissions.contains(perm);
13237                    if (permissionViolation) {
13238                        if (mPrivappPermissionsViolations == null) {
13239                            mPrivappPermissionsViolations = new ArraySet<>();
13240                        }
13241                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13242                    } else {
13243                        return false;
13244                    }
13245                }
13246                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13247                    return false;
13248                }
13249            }
13250        }
13251        boolean allowed = (compareSignatures(
13252                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13253                        == PackageManager.SIGNATURE_MATCH)
13254                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13255                        == PackageManager.SIGNATURE_MATCH);
13256        if (!allowed && privilegedPermission) {
13257            if (isSystemApp(pkg)) {
13258                // For updated system applications, a system permission
13259                // is granted only if it had been defined by the original application.
13260                if (pkg.isUpdatedSystemApp()) {
13261                    final PackageSetting sysPs = mSettings
13262                            .getDisabledSystemPkgLPr(pkg.packageName);
13263                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13264                        // If the original was granted this permission, we take
13265                        // that grant decision as read and propagate it to the
13266                        // update.
13267                        if (sysPs.isPrivileged()) {
13268                            allowed = true;
13269                        }
13270                    } else {
13271                        // The system apk may have been updated with an older
13272                        // version of the one on the data partition, but which
13273                        // granted a new system permission that it didn't have
13274                        // before.  In this case we do want to allow the app to
13275                        // now get the new permission if the ancestral apk is
13276                        // privileged to get it.
13277                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13278                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13279                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13280                                    allowed = true;
13281                                    break;
13282                                }
13283                            }
13284                        }
13285                        // Also if a privileged parent package on the system image or any of
13286                        // its children requested a privileged permission, the updated child
13287                        // packages can also get the permission.
13288                        if (pkg.parentPackage != null) {
13289                            final PackageSetting disabledSysParentPs = mSettings
13290                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13291                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13292                                    && disabledSysParentPs.isPrivileged()) {
13293                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13294                                    allowed = true;
13295                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13296                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13297                                    for (int i = 0; i < count; i++) {
13298                                        PackageParser.Package disabledSysChildPkg =
13299                                                disabledSysParentPs.pkg.childPackages.get(i);
13300                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13301                                                perm)) {
13302                                            allowed = true;
13303                                            break;
13304                                        }
13305                                    }
13306                                }
13307                            }
13308                        }
13309                    }
13310                } else {
13311                    allowed = isPrivilegedApp(pkg);
13312                }
13313            }
13314        }
13315        if (!allowed) {
13316            if (!allowed && (bp.protectionLevel
13317                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13318                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13319                // If this was a previously normal/dangerous permission that got moved
13320                // to a system permission as part of the runtime permission redesign, then
13321                // we still want to blindly grant it to old apps.
13322                allowed = true;
13323            }
13324            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13325                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13326                // If this permission is to be granted to the system installer and
13327                // this app is an installer, then it gets the permission.
13328                allowed = true;
13329            }
13330            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13331                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13332                // If this permission is to be granted to the system verifier and
13333                // this app is a verifier, then it gets the permission.
13334                allowed = true;
13335            }
13336            if (!allowed && (bp.protectionLevel
13337                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13338                    && isSystemApp(pkg)) {
13339                // Any pre-installed system app is allowed to get this permission.
13340                allowed = true;
13341            }
13342            if (!allowed && (bp.protectionLevel
13343                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13344                // For development permissions, a development permission
13345                // is granted only if it was already granted.
13346                allowed = origPermissions.hasInstallPermission(perm);
13347            }
13348            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13349                    && pkg.packageName.equals(mSetupWizardPackage)) {
13350                // If this permission is to be granted to the system setup wizard and
13351                // this app is a setup wizard, then it gets the permission.
13352                allowed = true;
13353            }
13354        }
13355        return allowed;
13356    }
13357
13358    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13359        final int permCount = pkg.requestedPermissions.size();
13360        for (int j = 0; j < permCount; j++) {
13361            String requestedPermission = pkg.requestedPermissions.get(j);
13362            if (permission.equals(requestedPermission)) {
13363                return true;
13364            }
13365        }
13366        return false;
13367    }
13368
13369    final class ActivityIntentResolver
13370            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13371        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13372                boolean defaultOnly, int userId) {
13373            if (!sUserManager.exists(userId)) return null;
13374            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13375            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13376        }
13377
13378        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13379                int userId) {
13380            if (!sUserManager.exists(userId)) return null;
13381            mFlags = flags;
13382            return super.queryIntent(intent, resolvedType,
13383                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13384                    userId);
13385        }
13386
13387        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13388                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13389            if (!sUserManager.exists(userId)) return null;
13390            if (packageActivities == null) {
13391                return null;
13392            }
13393            mFlags = flags;
13394            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13395            final int N = packageActivities.size();
13396            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13397                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13398
13399            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13400            for (int i = 0; i < N; ++i) {
13401                intentFilters = packageActivities.get(i).intents;
13402                if (intentFilters != null && intentFilters.size() > 0) {
13403                    PackageParser.ActivityIntentInfo[] array =
13404                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13405                    intentFilters.toArray(array);
13406                    listCut.add(array);
13407                }
13408            }
13409            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13410        }
13411
13412        /**
13413         * Finds a privileged activity that matches the specified activity names.
13414         */
13415        private PackageParser.Activity findMatchingActivity(
13416                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13417            for (PackageParser.Activity sysActivity : activityList) {
13418                if (sysActivity.info.name.equals(activityInfo.name)) {
13419                    return sysActivity;
13420                }
13421                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13422                    return sysActivity;
13423                }
13424                if (sysActivity.info.targetActivity != null) {
13425                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13426                        return sysActivity;
13427                    }
13428                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13429                        return sysActivity;
13430                    }
13431                }
13432            }
13433            return null;
13434        }
13435
13436        public class IterGenerator<E> {
13437            public Iterator<E> generate(ActivityIntentInfo info) {
13438                return null;
13439            }
13440        }
13441
13442        public class ActionIterGenerator extends IterGenerator<String> {
13443            @Override
13444            public Iterator<String> generate(ActivityIntentInfo info) {
13445                return info.actionsIterator();
13446            }
13447        }
13448
13449        public class CategoriesIterGenerator extends IterGenerator<String> {
13450            @Override
13451            public Iterator<String> generate(ActivityIntentInfo info) {
13452                return info.categoriesIterator();
13453            }
13454        }
13455
13456        public class SchemesIterGenerator extends IterGenerator<String> {
13457            @Override
13458            public Iterator<String> generate(ActivityIntentInfo info) {
13459                return info.schemesIterator();
13460            }
13461        }
13462
13463        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13464            @Override
13465            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13466                return info.authoritiesIterator();
13467            }
13468        }
13469
13470        /**
13471         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13472         * MODIFIED. Do not pass in a list that should not be changed.
13473         */
13474        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13475                IterGenerator<T> generator, Iterator<T> searchIterator) {
13476            // loop through the set of actions; every one must be found in the intent filter
13477            while (searchIterator.hasNext()) {
13478                // we must have at least one filter in the list to consider a match
13479                if (intentList.size() == 0) {
13480                    break;
13481                }
13482
13483                final T searchAction = searchIterator.next();
13484
13485                // loop through the set of intent filters
13486                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13487                while (intentIter.hasNext()) {
13488                    final ActivityIntentInfo intentInfo = intentIter.next();
13489                    boolean selectionFound = false;
13490
13491                    // loop through the intent filter's selection criteria; at least one
13492                    // of them must match the searched criteria
13493                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13494                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13495                        final T intentSelection = intentSelectionIter.next();
13496                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13497                            selectionFound = true;
13498                            break;
13499                        }
13500                    }
13501
13502                    // the selection criteria wasn't found in this filter's set; this filter
13503                    // is not a potential match
13504                    if (!selectionFound) {
13505                        intentIter.remove();
13506                    }
13507                }
13508            }
13509        }
13510
13511        private boolean isProtectedAction(ActivityIntentInfo filter) {
13512            final Iterator<String> actionsIter = filter.actionsIterator();
13513            while (actionsIter != null && actionsIter.hasNext()) {
13514                final String filterAction = actionsIter.next();
13515                if (PROTECTED_ACTIONS.contains(filterAction)) {
13516                    return true;
13517                }
13518            }
13519            return false;
13520        }
13521
13522        /**
13523         * Adjusts the priority of the given intent filter according to policy.
13524         * <p>
13525         * <ul>
13526         * <li>The priority for non privileged applications is capped to '0'</li>
13527         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13528         * <li>The priority for unbundled updates to privileged applications is capped to the
13529         *      priority defined on the system partition</li>
13530         * </ul>
13531         * <p>
13532         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13533         * allowed to obtain any priority on any action.
13534         */
13535        private void adjustPriority(
13536                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13537            // nothing to do; priority is fine as-is
13538            if (intent.getPriority() <= 0) {
13539                return;
13540            }
13541
13542            final ActivityInfo activityInfo = intent.activity.info;
13543            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13544
13545            final boolean privilegedApp =
13546                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13547            if (!privilegedApp) {
13548                // non-privileged applications can never define a priority >0
13549                if (DEBUG_FILTERS) {
13550                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13551                            + " package: " + applicationInfo.packageName
13552                            + " activity: " + intent.activity.className
13553                            + " origPrio: " + intent.getPriority());
13554                }
13555                intent.setPriority(0);
13556                return;
13557            }
13558
13559            if (systemActivities == null) {
13560                // the system package is not disabled; we're parsing the system partition
13561                if (isProtectedAction(intent)) {
13562                    if (mDeferProtectedFilters) {
13563                        // We can't deal with these just yet. No component should ever obtain a
13564                        // >0 priority for a protected actions, with ONE exception -- the setup
13565                        // wizard. The setup wizard, however, cannot be known until we're able to
13566                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13567                        // until all intent filters have been processed. Chicken, meet egg.
13568                        // Let the filter temporarily have a high priority and rectify the
13569                        // priorities after all system packages have been scanned.
13570                        mProtectedFilters.add(intent);
13571                        if (DEBUG_FILTERS) {
13572                            Slog.i(TAG, "Protected action; save for later;"
13573                                    + " package: " + applicationInfo.packageName
13574                                    + " activity: " + intent.activity.className
13575                                    + " origPrio: " + intent.getPriority());
13576                        }
13577                        return;
13578                    } else {
13579                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13580                            Slog.i(TAG, "No setup wizard;"
13581                                + " All protected intents capped to priority 0");
13582                        }
13583                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13584                            if (DEBUG_FILTERS) {
13585                                Slog.i(TAG, "Found setup wizard;"
13586                                    + " allow priority " + intent.getPriority() + ";"
13587                                    + " package: " + intent.activity.info.packageName
13588                                    + " activity: " + intent.activity.className
13589                                    + " priority: " + intent.getPriority());
13590                            }
13591                            // setup wizard gets whatever it wants
13592                            return;
13593                        }
13594                        if (DEBUG_FILTERS) {
13595                            Slog.i(TAG, "Protected action; cap priority to 0;"
13596                                    + " package: " + intent.activity.info.packageName
13597                                    + " activity: " + intent.activity.className
13598                                    + " origPrio: " + intent.getPriority());
13599                        }
13600                        intent.setPriority(0);
13601                        return;
13602                    }
13603                }
13604                // privileged apps on the system image get whatever priority they request
13605                return;
13606            }
13607
13608            // privileged app unbundled update ... try to find the same activity
13609            final PackageParser.Activity foundActivity =
13610                    findMatchingActivity(systemActivities, activityInfo);
13611            if (foundActivity == null) {
13612                // this is a new activity; it cannot obtain >0 priority
13613                if (DEBUG_FILTERS) {
13614                    Slog.i(TAG, "New activity; cap priority to 0;"
13615                            + " package: " + applicationInfo.packageName
13616                            + " activity: " + intent.activity.className
13617                            + " origPrio: " + intent.getPriority());
13618                }
13619                intent.setPriority(0);
13620                return;
13621            }
13622
13623            // found activity, now check for filter equivalence
13624
13625            // a shallow copy is enough; we modify the list, not its contents
13626            final List<ActivityIntentInfo> intentListCopy =
13627                    new ArrayList<>(foundActivity.intents);
13628            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13629
13630            // find matching action subsets
13631            final Iterator<String> actionsIterator = intent.actionsIterator();
13632            if (actionsIterator != null) {
13633                getIntentListSubset(
13634                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13635                if (intentListCopy.size() == 0) {
13636                    // no more intents to match; we're not equivalent
13637                    if (DEBUG_FILTERS) {
13638                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13639                                + " package: " + applicationInfo.packageName
13640                                + " activity: " + intent.activity.className
13641                                + " origPrio: " + intent.getPriority());
13642                    }
13643                    intent.setPriority(0);
13644                    return;
13645                }
13646            }
13647
13648            // find matching category subsets
13649            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13650            if (categoriesIterator != null) {
13651                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13652                        categoriesIterator);
13653                if (intentListCopy.size() == 0) {
13654                    // no more intents to match; we're not equivalent
13655                    if (DEBUG_FILTERS) {
13656                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13657                                + " package: " + applicationInfo.packageName
13658                                + " activity: " + intent.activity.className
13659                                + " origPrio: " + intent.getPriority());
13660                    }
13661                    intent.setPriority(0);
13662                    return;
13663                }
13664            }
13665
13666            // find matching schemes subsets
13667            final Iterator<String> schemesIterator = intent.schemesIterator();
13668            if (schemesIterator != null) {
13669                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13670                        schemesIterator);
13671                if (intentListCopy.size() == 0) {
13672                    // no more intents to match; we're not equivalent
13673                    if (DEBUG_FILTERS) {
13674                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13675                                + " package: " + applicationInfo.packageName
13676                                + " activity: " + intent.activity.className
13677                                + " origPrio: " + intent.getPriority());
13678                    }
13679                    intent.setPriority(0);
13680                    return;
13681                }
13682            }
13683
13684            // find matching authorities subsets
13685            final Iterator<IntentFilter.AuthorityEntry>
13686                    authoritiesIterator = intent.authoritiesIterator();
13687            if (authoritiesIterator != null) {
13688                getIntentListSubset(intentListCopy,
13689                        new AuthoritiesIterGenerator(),
13690                        authoritiesIterator);
13691                if (intentListCopy.size() == 0) {
13692                    // no more intents to match; we're not equivalent
13693                    if (DEBUG_FILTERS) {
13694                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13695                                + " package: " + applicationInfo.packageName
13696                                + " activity: " + intent.activity.className
13697                                + " origPrio: " + intent.getPriority());
13698                    }
13699                    intent.setPriority(0);
13700                    return;
13701                }
13702            }
13703
13704            // we found matching filter(s); app gets the max priority of all intents
13705            int cappedPriority = 0;
13706            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13707                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13708            }
13709            if (intent.getPriority() > cappedPriority) {
13710                if (DEBUG_FILTERS) {
13711                    Slog.i(TAG, "Found matching filter(s);"
13712                            + " cap priority to " + cappedPriority + ";"
13713                            + " package: " + applicationInfo.packageName
13714                            + " activity: " + intent.activity.className
13715                            + " origPrio: " + intent.getPriority());
13716                }
13717                intent.setPriority(cappedPriority);
13718                return;
13719            }
13720            // all this for nothing; the requested priority was <= what was on the system
13721        }
13722
13723        public final void addActivity(PackageParser.Activity a, String type) {
13724            mActivities.put(a.getComponentName(), a);
13725            if (DEBUG_SHOW_INFO)
13726                Log.v(
13727                TAG, "  " + type + " " +
13728                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13729            if (DEBUG_SHOW_INFO)
13730                Log.v(TAG, "    Class=" + a.info.name);
13731            final int NI = a.intents.size();
13732            for (int j=0; j<NI; j++) {
13733                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13734                if ("activity".equals(type)) {
13735                    final PackageSetting ps =
13736                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13737                    final List<PackageParser.Activity> systemActivities =
13738                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13739                    adjustPriority(systemActivities, intent);
13740                }
13741                if (DEBUG_SHOW_INFO) {
13742                    Log.v(TAG, "    IntentFilter:");
13743                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13744                }
13745                if (!intent.debugCheck()) {
13746                    Log.w(TAG, "==> For Activity " + a.info.name);
13747                }
13748                addFilter(intent);
13749            }
13750        }
13751
13752        public final void removeActivity(PackageParser.Activity a, String type) {
13753            mActivities.remove(a.getComponentName());
13754            if (DEBUG_SHOW_INFO) {
13755                Log.v(TAG, "  " + type + " "
13756                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13757                                : a.info.name) + ":");
13758                Log.v(TAG, "    Class=" + a.info.name);
13759            }
13760            final int NI = a.intents.size();
13761            for (int j=0; j<NI; j++) {
13762                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13763                if (DEBUG_SHOW_INFO) {
13764                    Log.v(TAG, "    IntentFilter:");
13765                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13766                }
13767                removeFilter(intent);
13768            }
13769        }
13770
13771        @Override
13772        protected boolean allowFilterResult(
13773                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13774            ActivityInfo filterAi = filter.activity.info;
13775            for (int i=dest.size()-1; i>=0; i--) {
13776                ActivityInfo destAi = dest.get(i).activityInfo;
13777                if (destAi.name == filterAi.name
13778                        && destAi.packageName == filterAi.packageName) {
13779                    return false;
13780                }
13781            }
13782            return true;
13783        }
13784
13785        @Override
13786        protected ActivityIntentInfo[] newArray(int size) {
13787            return new ActivityIntentInfo[size];
13788        }
13789
13790        @Override
13791        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13792            if (!sUserManager.exists(userId)) return true;
13793            PackageParser.Package p = filter.activity.owner;
13794            if (p != null) {
13795                PackageSetting ps = (PackageSetting)p.mExtras;
13796                if (ps != null) {
13797                    // System apps are never considered stopped for purposes of
13798                    // filtering, because there may be no way for the user to
13799                    // actually re-launch them.
13800                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13801                            && ps.getStopped(userId);
13802                }
13803            }
13804            return false;
13805        }
13806
13807        @Override
13808        protected boolean isPackageForFilter(String packageName,
13809                PackageParser.ActivityIntentInfo info) {
13810            return packageName.equals(info.activity.owner.packageName);
13811        }
13812
13813        @Override
13814        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13815                int match, int userId) {
13816            if (!sUserManager.exists(userId)) return null;
13817            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13818                return null;
13819            }
13820            final PackageParser.Activity activity = info.activity;
13821            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13822            if (ps == null) {
13823                return null;
13824            }
13825            final PackageUserState userState = ps.readUserState(userId);
13826            ActivityInfo ai =
13827                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13828            if (ai == null) {
13829                return null;
13830            }
13831            final boolean matchExplicitlyVisibleOnly =
13832                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13833            final boolean matchVisibleToInstantApp =
13834                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13835            final boolean componentVisible =
13836                    matchVisibleToInstantApp
13837                    && info.isVisibleToInstantApp()
13838                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13839            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13840            // throw out filters that aren't visible to ephemeral apps
13841            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13842                return null;
13843            }
13844            // throw out instant app filters if we're not explicitly requesting them
13845            if (!matchInstantApp && userState.instantApp) {
13846                return null;
13847            }
13848            // throw out instant app filters if updates are available; will trigger
13849            // instant app resolution
13850            if (userState.instantApp && ps.isUpdateAvailable()) {
13851                return null;
13852            }
13853            final ResolveInfo res = new ResolveInfo();
13854            res.activityInfo = ai;
13855            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13856                res.filter = info;
13857            }
13858            if (info != null) {
13859                res.handleAllWebDataURI = info.handleAllWebDataURI();
13860            }
13861            res.priority = info.getPriority();
13862            res.preferredOrder = activity.owner.mPreferredOrder;
13863            //System.out.println("Result: " + res.activityInfo.className +
13864            //                   " = " + res.priority);
13865            res.match = match;
13866            res.isDefault = info.hasDefault;
13867            res.labelRes = info.labelRes;
13868            res.nonLocalizedLabel = info.nonLocalizedLabel;
13869            if (userNeedsBadging(userId)) {
13870                res.noResourceId = true;
13871            } else {
13872                res.icon = info.icon;
13873            }
13874            res.iconResourceId = info.icon;
13875            res.system = res.activityInfo.applicationInfo.isSystemApp();
13876            res.isInstantAppAvailable = userState.instantApp;
13877            return res;
13878        }
13879
13880        @Override
13881        protected void sortResults(List<ResolveInfo> results) {
13882            Collections.sort(results, mResolvePrioritySorter);
13883        }
13884
13885        @Override
13886        protected void dumpFilter(PrintWriter out, String prefix,
13887                PackageParser.ActivityIntentInfo filter) {
13888            out.print(prefix); out.print(
13889                    Integer.toHexString(System.identityHashCode(filter.activity)));
13890                    out.print(' ');
13891                    filter.activity.printComponentShortName(out);
13892                    out.print(" filter ");
13893                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13894        }
13895
13896        @Override
13897        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13898            return filter.activity;
13899        }
13900
13901        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13902            PackageParser.Activity activity = (PackageParser.Activity)label;
13903            out.print(prefix); out.print(
13904                    Integer.toHexString(System.identityHashCode(activity)));
13905                    out.print(' ');
13906                    activity.printComponentShortName(out);
13907            if (count > 1) {
13908                out.print(" ("); out.print(count); out.print(" filters)");
13909            }
13910            out.println();
13911        }
13912
13913        // Keys are String (activity class name), values are Activity.
13914        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13915                = new ArrayMap<ComponentName, PackageParser.Activity>();
13916        private int mFlags;
13917    }
13918
13919    private final class ServiceIntentResolver
13920            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13921        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13922                boolean defaultOnly, int userId) {
13923            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13924            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13925        }
13926
13927        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13928                int userId) {
13929            if (!sUserManager.exists(userId)) return null;
13930            mFlags = flags;
13931            return super.queryIntent(intent, resolvedType,
13932                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13933                    userId);
13934        }
13935
13936        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13937                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13938            if (!sUserManager.exists(userId)) return null;
13939            if (packageServices == null) {
13940                return null;
13941            }
13942            mFlags = flags;
13943            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13944            final int N = packageServices.size();
13945            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13946                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13947
13948            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13949            for (int i = 0; i < N; ++i) {
13950                intentFilters = packageServices.get(i).intents;
13951                if (intentFilters != null && intentFilters.size() > 0) {
13952                    PackageParser.ServiceIntentInfo[] array =
13953                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13954                    intentFilters.toArray(array);
13955                    listCut.add(array);
13956                }
13957            }
13958            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13959        }
13960
13961        public final void addService(PackageParser.Service s) {
13962            mServices.put(s.getComponentName(), s);
13963            if (DEBUG_SHOW_INFO) {
13964                Log.v(TAG, "  "
13965                        + (s.info.nonLocalizedLabel != null
13966                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13967                Log.v(TAG, "    Class=" + s.info.name);
13968            }
13969            final int NI = s.intents.size();
13970            int j;
13971            for (j=0; j<NI; j++) {
13972                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13973                if (DEBUG_SHOW_INFO) {
13974                    Log.v(TAG, "    IntentFilter:");
13975                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13976                }
13977                if (!intent.debugCheck()) {
13978                    Log.w(TAG, "==> For Service " + s.info.name);
13979                }
13980                addFilter(intent);
13981            }
13982        }
13983
13984        public final void removeService(PackageParser.Service s) {
13985            mServices.remove(s.getComponentName());
13986            if (DEBUG_SHOW_INFO) {
13987                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13988                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13989                Log.v(TAG, "    Class=" + s.info.name);
13990            }
13991            final int NI = s.intents.size();
13992            int j;
13993            for (j=0; j<NI; j++) {
13994                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13995                if (DEBUG_SHOW_INFO) {
13996                    Log.v(TAG, "    IntentFilter:");
13997                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13998                }
13999                removeFilter(intent);
14000            }
14001        }
14002
14003        @Override
14004        protected boolean allowFilterResult(
14005                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
14006            ServiceInfo filterSi = filter.service.info;
14007            for (int i=dest.size()-1; i>=0; i--) {
14008                ServiceInfo destAi = dest.get(i).serviceInfo;
14009                if (destAi.name == filterSi.name
14010                        && destAi.packageName == filterSi.packageName) {
14011                    return false;
14012                }
14013            }
14014            return true;
14015        }
14016
14017        @Override
14018        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
14019            return new PackageParser.ServiceIntentInfo[size];
14020        }
14021
14022        @Override
14023        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
14024            if (!sUserManager.exists(userId)) return true;
14025            PackageParser.Package p = filter.service.owner;
14026            if (p != null) {
14027                PackageSetting ps = (PackageSetting)p.mExtras;
14028                if (ps != null) {
14029                    // System apps are never considered stopped for purposes of
14030                    // filtering, because there may be no way for the user to
14031                    // actually re-launch them.
14032                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14033                            && ps.getStopped(userId);
14034                }
14035            }
14036            return false;
14037        }
14038
14039        @Override
14040        protected boolean isPackageForFilter(String packageName,
14041                PackageParser.ServiceIntentInfo info) {
14042            return packageName.equals(info.service.owner.packageName);
14043        }
14044
14045        @Override
14046        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14047                int match, int userId) {
14048            if (!sUserManager.exists(userId)) return null;
14049            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14050            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14051                return null;
14052            }
14053            final PackageParser.Service service = info.service;
14054            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14055            if (ps == null) {
14056                return null;
14057            }
14058            final PackageUserState userState = ps.readUserState(userId);
14059            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14060                    userState, userId);
14061            if (si == null) {
14062                return null;
14063            }
14064            final boolean matchVisibleToInstantApp =
14065                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14066            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14067            // throw out filters that aren't visible to ephemeral apps
14068            if (matchVisibleToInstantApp
14069                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14070                return null;
14071            }
14072            // throw out ephemeral filters if we're not explicitly requesting them
14073            if (!isInstantApp && userState.instantApp) {
14074                return null;
14075            }
14076            // throw out instant app filters if updates are available; will trigger
14077            // instant app resolution
14078            if (userState.instantApp && ps.isUpdateAvailable()) {
14079                return null;
14080            }
14081            final ResolveInfo res = new ResolveInfo();
14082            res.serviceInfo = si;
14083            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14084                res.filter = filter;
14085            }
14086            res.priority = info.getPriority();
14087            res.preferredOrder = service.owner.mPreferredOrder;
14088            res.match = match;
14089            res.isDefault = info.hasDefault;
14090            res.labelRes = info.labelRes;
14091            res.nonLocalizedLabel = info.nonLocalizedLabel;
14092            res.icon = info.icon;
14093            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14094            return res;
14095        }
14096
14097        @Override
14098        protected void sortResults(List<ResolveInfo> results) {
14099            Collections.sort(results, mResolvePrioritySorter);
14100        }
14101
14102        @Override
14103        protected void dumpFilter(PrintWriter out, String prefix,
14104                PackageParser.ServiceIntentInfo filter) {
14105            out.print(prefix); out.print(
14106                    Integer.toHexString(System.identityHashCode(filter.service)));
14107                    out.print(' ');
14108                    filter.service.printComponentShortName(out);
14109                    out.print(" filter ");
14110                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14111        }
14112
14113        @Override
14114        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14115            return filter.service;
14116        }
14117
14118        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14119            PackageParser.Service service = (PackageParser.Service)label;
14120            out.print(prefix); out.print(
14121                    Integer.toHexString(System.identityHashCode(service)));
14122                    out.print(' ');
14123                    service.printComponentShortName(out);
14124            if (count > 1) {
14125                out.print(" ("); out.print(count); out.print(" filters)");
14126            }
14127            out.println();
14128        }
14129
14130//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14131//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14132//            final List<ResolveInfo> retList = Lists.newArrayList();
14133//            while (i.hasNext()) {
14134//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14135//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14136//                    retList.add(resolveInfo);
14137//                }
14138//            }
14139//            return retList;
14140//        }
14141
14142        // Keys are String (activity class name), values are Activity.
14143        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14144                = new ArrayMap<ComponentName, PackageParser.Service>();
14145        private int mFlags;
14146    }
14147
14148    private final class ProviderIntentResolver
14149            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14150        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14151                boolean defaultOnly, int userId) {
14152            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14153            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14154        }
14155
14156        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14157                int userId) {
14158            if (!sUserManager.exists(userId))
14159                return null;
14160            mFlags = flags;
14161            return super.queryIntent(intent, resolvedType,
14162                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14163                    userId);
14164        }
14165
14166        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14167                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14168            if (!sUserManager.exists(userId))
14169                return null;
14170            if (packageProviders == null) {
14171                return null;
14172            }
14173            mFlags = flags;
14174            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14175            final int N = packageProviders.size();
14176            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14177                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14178
14179            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14180            for (int i = 0; i < N; ++i) {
14181                intentFilters = packageProviders.get(i).intents;
14182                if (intentFilters != null && intentFilters.size() > 0) {
14183                    PackageParser.ProviderIntentInfo[] array =
14184                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14185                    intentFilters.toArray(array);
14186                    listCut.add(array);
14187                }
14188            }
14189            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14190        }
14191
14192        public final void addProvider(PackageParser.Provider p) {
14193            if (mProviders.containsKey(p.getComponentName())) {
14194                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14195                return;
14196            }
14197
14198            mProviders.put(p.getComponentName(), p);
14199            if (DEBUG_SHOW_INFO) {
14200                Log.v(TAG, "  "
14201                        + (p.info.nonLocalizedLabel != null
14202                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14203                Log.v(TAG, "    Class=" + p.info.name);
14204            }
14205            final int NI = p.intents.size();
14206            int j;
14207            for (j = 0; j < NI; j++) {
14208                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14209                if (DEBUG_SHOW_INFO) {
14210                    Log.v(TAG, "    IntentFilter:");
14211                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14212                }
14213                if (!intent.debugCheck()) {
14214                    Log.w(TAG, "==> For Provider " + p.info.name);
14215                }
14216                addFilter(intent);
14217            }
14218        }
14219
14220        public final void removeProvider(PackageParser.Provider p) {
14221            mProviders.remove(p.getComponentName());
14222            if (DEBUG_SHOW_INFO) {
14223                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14224                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14225                Log.v(TAG, "    Class=" + p.info.name);
14226            }
14227            final int NI = p.intents.size();
14228            int j;
14229            for (j = 0; j < NI; j++) {
14230                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14231                if (DEBUG_SHOW_INFO) {
14232                    Log.v(TAG, "    IntentFilter:");
14233                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14234                }
14235                removeFilter(intent);
14236            }
14237        }
14238
14239        @Override
14240        protected boolean allowFilterResult(
14241                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14242            ProviderInfo filterPi = filter.provider.info;
14243            for (int i = dest.size() - 1; i >= 0; i--) {
14244                ProviderInfo destPi = dest.get(i).providerInfo;
14245                if (destPi.name == filterPi.name
14246                        && destPi.packageName == filterPi.packageName) {
14247                    return false;
14248                }
14249            }
14250            return true;
14251        }
14252
14253        @Override
14254        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14255            return new PackageParser.ProviderIntentInfo[size];
14256        }
14257
14258        @Override
14259        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14260            if (!sUserManager.exists(userId))
14261                return true;
14262            PackageParser.Package p = filter.provider.owner;
14263            if (p != null) {
14264                PackageSetting ps = (PackageSetting) p.mExtras;
14265                if (ps != null) {
14266                    // System apps are never considered stopped for purposes of
14267                    // filtering, because there may be no way for the user to
14268                    // actually re-launch them.
14269                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14270                            && ps.getStopped(userId);
14271                }
14272            }
14273            return false;
14274        }
14275
14276        @Override
14277        protected boolean isPackageForFilter(String packageName,
14278                PackageParser.ProviderIntentInfo info) {
14279            return packageName.equals(info.provider.owner.packageName);
14280        }
14281
14282        @Override
14283        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14284                int match, int userId) {
14285            if (!sUserManager.exists(userId))
14286                return null;
14287            final PackageParser.ProviderIntentInfo info = filter;
14288            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14289                return null;
14290            }
14291            final PackageParser.Provider provider = info.provider;
14292            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14293            if (ps == null) {
14294                return null;
14295            }
14296            final PackageUserState userState = ps.readUserState(userId);
14297            final boolean matchVisibleToInstantApp =
14298                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14299            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14300            // throw out filters that aren't visible to instant applications
14301            if (matchVisibleToInstantApp
14302                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14303                return null;
14304            }
14305            // throw out instant application filters if we're not explicitly requesting them
14306            if (!isInstantApp && userState.instantApp) {
14307                return null;
14308            }
14309            // throw out instant application filters if updates are available; will trigger
14310            // instant application resolution
14311            if (userState.instantApp && ps.isUpdateAvailable()) {
14312                return null;
14313            }
14314            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14315                    userState, userId);
14316            if (pi == null) {
14317                return null;
14318            }
14319            final ResolveInfo res = new ResolveInfo();
14320            res.providerInfo = pi;
14321            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14322                res.filter = filter;
14323            }
14324            res.priority = info.getPriority();
14325            res.preferredOrder = provider.owner.mPreferredOrder;
14326            res.match = match;
14327            res.isDefault = info.hasDefault;
14328            res.labelRes = info.labelRes;
14329            res.nonLocalizedLabel = info.nonLocalizedLabel;
14330            res.icon = info.icon;
14331            res.system = res.providerInfo.applicationInfo.isSystemApp();
14332            return res;
14333        }
14334
14335        @Override
14336        protected void sortResults(List<ResolveInfo> results) {
14337            Collections.sort(results, mResolvePrioritySorter);
14338        }
14339
14340        @Override
14341        protected void dumpFilter(PrintWriter out, String prefix,
14342                PackageParser.ProviderIntentInfo filter) {
14343            out.print(prefix);
14344            out.print(
14345                    Integer.toHexString(System.identityHashCode(filter.provider)));
14346            out.print(' ');
14347            filter.provider.printComponentShortName(out);
14348            out.print(" filter ");
14349            out.println(Integer.toHexString(System.identityHashCode(filter)));
14350        }
14351
14352        @Override
14353        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14354            return filter.provider;
14355        }
14356
14357        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14358            PackageParser.Provider provider = (PackageParser.Provider)label;
14359            out.print(prefix); out.print(
14360                    Integer.toHexString(System.identityHashCode(provider)));
14361                    out.print(' ');
14362                    provider.printComponentShortName(out);
14363            if (count > 1) {
14364                out.print(" ("); out.print(count); out.print(" filters)");
14365            }
14366            out.println();
14367        }
14368
14369        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14370                = new ArrayMap<ComponentName, PackageParser.Provider>();
14371        private int mFlags;
14372    }
14373
14374    static final class EphemeralIntentResolver
14375            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14376        /**
14377         * The result that has the highest defined order. Ordering applies on a
14378         * per-package basis. Mapping is from package name to Pair of order and
14379         * EphemeralResolveInfo.
14380         * <p>
14381         * NOTE: This is implemented as a field variable for convenience and efficiency.
14382         * By having a field variable, we're able to track filter ordering as soon as
14383         * a non-zero order is defined. Otherwise, multiple loops across the result set
14384         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14385         * this needs to be contained entirely within {@link #filterResults}.
14386         */
14387        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14388
14389        @Override
14390        protected AuxiliaryResolveInfo[] newArray(int size) {
14391            return new AuxiliaryResolveInfo[size];
14392        }
14393
14394        @Override
14395        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14396            return true;
14397        }
14398
14399        @Override
14400        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14401                int userId) {
14402            if (!sUserManager.exists(userId)) {
14403                return null;
14404            }
14405            final String packageName = responseObj.resolveInfo.getPackageName();
14406            final Integer order = responseObj.getOrder();
14407            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14408                    mOrderResult.get(packageName);
14409            // ordering is enabled and this item's order isn't high enough
14410            if (lastOrderResult != null && lastOrderResult.first >= order) {
14411                return null;
14412            }
14413            final InstantAppResolveInfo res = responseObj.resolveInfo;
14414            if (order > 0) {
14415                // non-zero order, enable ordering
14416                mOrderResult.put(packageName, new Pair<>(order, res));
14417            }
14418            return responseObj;
14419        }
14420
14421        @Override
14422        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14423            // only do work if ordering is enabled [most of the time it won't be]
14424            if (mOrderResult.size() == 0) {
14425                return;
14426            }
14427            int resultSize = results.size();
14428            for (int i = 0; i < resultSize; i++) {
14429                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14430                final String packageName = info.getPackageName();
14431                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14432                if (savedInfo == null) {
14433                    // package doesn't having ordering
14434                    continue;
14435                }
14436                if (savedInfo.second == info) {
14437                    // circled back to the highest ordered item; remove from order list
14438                    mOrderResult.remove(packageName);
14439                    if (mOrderResult.size() == 0) {
14440                        // no more ordered items
14441                        break;
14442                    }
14443                    continue;
14444                }
14445                // item has a worse order, remove it from the result list
14446                results.remove(i);
14447                resultSize--;
14448                i--;
14449            }
14450        }
14451    }
14452
14453    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14454            new Comparator<ResolveInfo>() {
14455        public int compare(ResolveInfo r1, ResolveInfo r2) {
14456            int v1 = r1.priority;
14457            int v2 = r2.priority;
14458            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14459            if (v1 != v2) {
14460                return (v1 > v2) ? -1 : 1;
14461            }
14462            v1 = r1.preferredOrder;
14463            v2 = r2.preferredOrder;
14464            if (v1 != v2) {
14465                return (v1 > v2) ? -1 : 1;
14466            }
14467            if (r1.isDefault != r2.isDefault) {
14468                return r1.isDefault ? -1 : 1;
14469            }
14470            v1 = r1.match;
14471            v2 = r2.match;
14472            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14473            if (v1 != v2) {
14474                return (v1 > v2) ? -1 : 1;
14475            }
14476            if (r1.system != r2.system) {
14477                return r1.system ? -1 : 1;
14478            }
14479            if (r1.activityInfo != null) {
14480                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14481            }
14482            if (r1.serviceInfo != null) {
14483                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14484            }
14485            if (r1.providerInfo != null) {
14486                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14487            }
14488            return 0;
14489        }
14490    };
14491
14492    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14493            new Comparator<ProviderInfo>() {
14494        public int compare(ProviderInfo p1, ProviderInfo p2) {
14495            final int v1 = p1.initOrder;
14496            final int v2 = p2.initOrder;
14497            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14498        }
14499    };
14500
14501    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14502            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14503            final int[] userIds) {
14504        mHandler.post(new Runnable() {
14505            @Override
14506            public void run() {
14507                try {
14508                    final IActivityManager am = ActivityManager.getService();
14509                    if (am == null) return;
14510                    final int[] resolvedUserIds;
14511                    if (userIds == null) {
14512                        resolvedUserIds = am.getRunningUserIds();
14513                    } else {
14514                        resolvedUserIds = userIds;
14515                    }
14516                    for (int id : resolvedUserIds) {
14517                        final Intent intent = new Intent(action,
14518                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14519                        if (extras != null) {
14520                            intent.putExtras(extras);
14521                        }
14522                        if (targetPkg != null) {
14523                            intent.setPackage(targetPkg);
14524                        }
14525                        // Modify the UID when posting to other users
14526                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14527                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14528                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14529                            intent.putExtra(Intent.EXTRA_UID, uid);
14530                        }
14531                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14532                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14533                        if (DEBUG_BROADCASTS) {
14534                            RuntimeException here = new RuntimeException("here");
14535                            here.fillInStackTrace();
14536                            Slog.d(TAG, "Sending to user " + id + ": "
14537                                    + intent.toShortString(false, true, false, false)
14538                                    + " " + intent.getExtras(), here);
14539                        }
14540                        am.broadcastIntent(null, intent, null, finishedReceiver,
14541                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14542                                null, finishedReceiver != null, false, id);
14543                    }
14544                } catch (RemoteException ex) {
14545                }
14546            }
14547        });
14548    }
14549
14550    /**
14551     * Check if the external storage media is available. This is true if there
14552     * is a mounted external storage medium or if the external storage is
14553     * emulated.
14554     */
14555    private boolean isExternalMediaAvailable() {
14556        return mMediaMounted || Environment.isExternalStorageEmulated();
14557    }
14558
14559    @Override
14560    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14561        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14562            return null;
14563        }
14564        // writer
14565        synchronized (mPackages) {
14566            if (!isExternalMediaAvailable()) {
14567                // If the external storage is no longer mounted at this point,
14568                // the caller may not have been able to delete all of this
14569                // packages files and can not delete any more.  Bail.
14570                return null;
14571            }
14572            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14573            if (lastPackage != null) {
14574                pkgs.remove(lastPackage);
14575            }
14576            if (pkgs.size() > 0) {
14577                return pkgs.get(0);
14578            }
14579        }
14580        return null;
14581    }
14582
14583    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14584        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14585                userId, andCode ? 1 : 0, packageName);
14586        if (mSystemReady) {
14587            msg.sendToTarget();
14588        } else {
14589            if (mPostSystemReadyMessages == null) {
14590                mPostSystemReadyMessages = new ArrayList<>();
14591            }
14592            mPostSystemReadyMessages.add(msg);
14593        }
14594    }
14595
14596    void startCleaningPackages() {
14597        // reader
14598        if (!isExternalMediaAvailable()) {
14599            return;
14600        }
14601        synchronized (mPackages) {
14602            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14603                return;
14604            }
14605        }
14606        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14607        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14608        IActivityManager am = ActivityManager.getService();
14609        if (am != null) {
14610            int dcsUid = -1;
14611            synchronized (mPackages) {
14612                if (!mDefaultContainerWhitelisted) {
14613                    mDefaultContainerWhitelisted = true;
14614                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14615                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14616                }
14617            }
14618            try {
14619                if (dcsUid > 0) {
14620                    am.backgroundWhitelistUid(dcsUid);
14621                }
14622                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14623                        UserHandle.USER_SYSTEM);
14624            } catch (RemoteException e) {
14625            }
14626        }
14627    }
14628
14629    @Override
14630    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14631            int installFlags, String installerPackageName, int userId) {
14632        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14633
14634        final int callingUid = Binder.getCallingUid();
14635        enforceCrossUserPermission(callingUid, userId,
14636                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14637
14638        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14639            try {
14640                if (observer != null) {
14641                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14642                }
14643            } catch (RemoteException re) {
14644            }
14645            return;
14646        }
14647
14648        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14649            installFlags |= PackageManager.INSTALL_FROM_ADB;
14650
14651        } else {
14652            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14653            // about installerPackageName.
14654
14655            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14656            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14657        }
14658
14659        UserHandle user;
14660        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14661            user = UserHandle.ALL;
14662        } else {
14663            user = new UserHandle(userId);
14664        }
14665
14666        // Only system components can circumvent runtime permissions when installing.
14667        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14668                && mContext.checkCallingOrSelfPermission(Manifest.permission
14669                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14670            throw new SecurityException("You need the "
14671                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14672                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14673        }
14674
14675        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14676                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14677            throw new IllegalArgumentException(
14678                    "New installs into ASEC containers no longer supported");
14679        }
14680
14681        final File originFile = new File(originPath);
14682        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14683
14684        final Message msg = mHandler.obtainMessage(INIT_COPY);
14685        final VerificationInfo verificationInfo = new VerificationInfo(
14686                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14687        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14688                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14689                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14690                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14691        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14692        msg.obj = params;
14693
14694        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14695                System.identityHashCode(msg.obj));
14696        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14697                System.identityHashCode(msg.obj));
14698
14699        mHandler.sendMessage(msg);
14700    }
14701
14702
14703    /**
14704     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14705     * it is acting on behalf on an enterprise or the user).
14706     *
14707     * Note that the ordering of the conditionals in this method is important. The checks we perform
14708     * are as follows, in this order:
14709     *
14710     * 1) If the install is being performed by a system app, we can trust the app to have set the
14711     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14712     *    what it is.
14713     * 2) If the install is being performed by a device or profile owner app, the install reason
14714     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14715     *    set the install reason correctly. If the app targets an older SDK version where install
14716     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14717     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14718     * 3) In all other cases, the install is being performed by a regular app that is neither part
14719     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14720     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14721     *    set to enterprise policy and if so, change it to unknown instead.
14722     */
14723    private int fixUpInstallReason(String installerPackageName, int installerUid,
14724            int installReason) {
14725        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14726                == PERMISSION_GRANTED) {
14727            // If the install is being performed by a system app, we trust that app to have set the
14728            // install reason correctly.
14729            return installReason;
14730        }
14731
14732        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14733            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14734        if (dpm != null) {
14735            ComponentName owner = null;
14736            try {
14737                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14738                if (owner == null) {
14739                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14740                }
14741            } catch (RemoteException e) {
14742            }
14743            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14744                // If the install is being performed by a device or profile owner, the install
14745                // reason should be enterprise policy.
14746                return PackageManager.INSTALL_REASON_POLICY;
14747            }
14748        }
14749
14750        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14751            // If the install is being performed by a regular app (i.e. neither system app nor
14752            // device or profile owner), we have no reason to believe that the app is acting on
14753            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14754            // change it to unknown instead.
14755            return PackageManager.INSTALL_REASON_UNKNOWN;
14756        }
14757
14758        // If the install is being performed by a regular app and the install reason was set to any
14759        // value but enterprise policy, leave the install reason unchanged.
14760        return installReason;
14761    }
14762
14763    void installStage(String packageName, File stagedDir, String stagedCid,
14764            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14765            String installerPackageName, int installerUid, UserHandle user,
14766            Certificate[][] certificates) {
14767        if (DEBUG_EPHEMERAL) {
14768            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14769                Slog.d(TAG, "Ephemeral install of " + packageName);
14770            }
14771        }
14772        final VerificationInfo verificationInfo = new VerificationInfo(
14773                sessionParams.originatingUri, sessionParams.referrerUri,
14774                sessionParams.originatingUid, installerUid);
14775
14776        final OriginInfo origin;
14777        if (stagedDir != null) {
14778            origin = OriginInfo.fromStagedFile(stagedDir);
14779        } else {
14780            origin = OriginInfo.fromStagedContainer(stagedCid);
14781        }
14782
14783        final Message msg = mHandler.obtainMessage(INIT_COPY);
14784        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14785                sessionParams.installReason);
14786        final InstallParams params = new InstallParams(origin, null, observer,
14787                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14788                verificationInfo, user, sessionParams.abiOverride,
14789                sessionParams.grantedRuntimePermissions, certificates, installReason);
14790        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14791        msg.obj = params;
14792
14793        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14794                System.identityHashCode(msg.obj));
14795        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14796                System.identityHashCode(msg.obj));
14797
14798        mHandler.sendMessage(msg);
14799    }
14800
14801    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14802            int userId) {
14803        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14804        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14805                false /*startReceiver*/, pkgSetting.appId, userId);
14806
14807        // Send a session commit broadcast
14808        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14809        info.installReason = pkgSetting.getInstallReason(userId);
14810        info.appPackageName = packageName;
14811        sendSessionCommitBroadcast(info, userId);
14812    }
14813
14814    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14815            boolean includeStopped, int appId, int... userIds) {
14816        if (ArrayUtils.isEmpty(userIds)) {
14817            return;
14818        }
14819        Bundle extras = new Bundle(1);
14820        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14821        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14822
14823        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14824                packageName, extras, 0, null, null, userIds);
14825        if (sendBootCompleted) {
14826            mHandler.post(() -> {
14827                        for (int userId : userIds) {
14828                            sendBootCompletedBroadcastToSystemApp(
14829                                    packageName, includeStopped, userId);
14830                        }
14831                    }
14832            );
14833        }
14834    }
14835
14836    /**
14837     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14838     * automatically without needing an explicit launch.
14839     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14840     */
14841    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14842            int userId) {
14843        // If user is not running, the app didn't miss any broadcast
14844        if (!mUserManagerInternal.isUserRunning(userId)) {
14845            return;
14846        }
14847        final IActivityManager am = ActivityManager.getService();
14848        try {
14849            // Deliver LOCKED_BOOT_COMPLETED first
14850            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14851                    .setPackage(packageName);
14852            if (includeStopped) {
14853                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14854            }
14855            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14856            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14857                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14858
14859            // Deliver BOOT_COMPLETED only if user is unlocked
14860            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14861                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14862                if (includeStopped) {
14863                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14864                }
14865                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14866                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14867            }
14868        } catch (RemoteException e) {
14869            throw e.rethrowFromSystemServer();
14870        }
14871    }
14872
14873    @Override
14874    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14875            int userId) {
14876        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14877        PackageSetting pkgSetting;
14878        final int callingUid = Binder.getCallingUid();
14879        enforceCrossUserPermission(callingUid, userId,
14880                true /* requireFullPermission */, true /* checkShell */,
14881                "setApplicationHiddenSetting for user " + userId);
14882
14883        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14884            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14885            return false;
14886        }
14887
14888        long callingId = Binder.clearCallingIdentity();
14889        try {
14890            boolean sendAdded = false;
14891            boolean sendRemoved = false;
14892            // writer
14893            synchronized (mPackages) {
14894                pkgSetting = mSettings.mPackages.get(packageName);
14895                if (pkgSetting == null) {
14896                    return false;
14897                }
14898                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14899                    return false;
14900                }
14901                // Do not allow "android" is being disabled
14902                if ("android".equals(packageName)) {
14903                    Slog.w(TAG, "Cannot hide package: android");
14904                    return false;
14905                }
14906                // Cannot hide static shared libs as they are considered
14907                // a part of the using app (emulating static linking). Also
14908                // static libs are installed always on internal storage.
14909                PackageParser.Package pkg = mPackages.get(packageName);
14910                if (pkg != null && pkg.staticSharedLibName != null) {
14911                    Slog.w(TAG, "Cannot hide package: " + packageName
14912                            + " providing static shared library: "
14913                            + pkg.staticSharedLibName);
14914                    return false;
14915                }
14916                // Only allow protected packages to hide themselves.
14917                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14918                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14919                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14920                    return false;
14921                }
14922
14923                if (pkgSetting.getHidden(userId) != hidden) {
14924                    pkgSetting.setHidden(hidden, userId);
14925                    mSettings.writePackageRestrictionsLPr(userId);
14926                    if (hidden) {
14927                        sendRemoved = true;
14928                    } else {
14929                        sendAdded = true;
14930                    }
14931                }
14932            }
14933            if (sendAdded) {
14934                sendPackageAddedForUser(packageName, pkgSetting, userId);
14935                return true;
14936            }
14937            if (sendRemoved) {
14938                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14939                        "hiding pkg");
14940                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14941                return true;
14942            }
14943        } finally {
14944            Binder.restoreCallingIdentity(callingId);
14945        }
14946        return false;
14947    }
14948
14949    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14950            int userId) {
14951        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14952        info.removedPackage = packageName;
14953        info.installerPackageName = pkgSetting.installerPackageName;
14954        info.removedUsers = new int[] {userId};
14955        info.broadcastUsers = new int[] {userId};
14956        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14957        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14958    }
14959
14960    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14961        if (pkgList.length > 0) {
14962            Bundle extras = new Bundle(1);
14963            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14964
14965            sendPackageBroadcast(
14966                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14967                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14968                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14969                    new int[] {userId});
14970        }
14971    }
14972
14973    /**
14974     * Returns true if application is not found or there was an error. Otherwise it returns
14975     * the hidden state of the package for the given user.
14976     */
14977    @Override
14978    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14979        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14980        final int callingUid = Binder.getCallingUid();
14981        enforceCrossUserPermission(callingUid, userId,
14982                true /* requireFullPermission */, false /* checkShell */,
14983                "getApplicationHidden for user " + userId);
14984        PackageSetting ps;
14985        long callingId = Binder.clearCallingIdentity();
14986        try {
14987            // writer
14988            synchronized (mPackages) {
14989                ps = mSettings.mPackages.get(packageName);
14990                if (ps == null) {
14991                    return true;
14992                }
14993                if (filterAppAccessLPr(ps, callingUid, userId)) {
14994                    return true;
14995                }
14996                return ps.getHidden(userId);
14997            }
14998        } finally {
14999            Binder.restoreCallingIdentity(callingId);
15000        }
15001    }
15002
15003    /**
15004     * @hide
15005     */
15006    @Override
15007    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
15008            int installReason) {
15009        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
15010                null);
15011        PackageSetting pkgSetting;
15012        final int callingUid = Binder.getCallingUid();
15013        enforceCrossUserPermission(callingUid, userId,
15014                true /* requireFullPermission */, true /* checkShell */,
15015                "installExistingPackage for user " + userId);
15016        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
15017            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
15018        }
15019
15020        long callingId = Binder.clearCallingIdentity();
15021        try {
15022            boolean installed = false;
15023            final boolean instantApp =
15024                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15025            final boolean fullApp =
15026                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
15027
15028            // writer
15029            synchronized (mPackages) {
15030                pkgSetting = mSettings.mPackages.get(packageName);
15031                if (pkgSetting == null) {
15032                    return PackageManager.INSTALL_FAILED_INVALID_URI;
15033                }
15034                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15035                    // only allow the existing package to be used if it's installed as a full
15036                    // application for at least one user
15037                    boolean installAllowed = false;
15038                    for (int checkUserId : sUserManager.getUserIds()) {
15039                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15040                        if (installAllowed) {
15041                            break;
15042                        }
15043                    }
15044                    if (!installAllowed) {
15045                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15046                    }
15047                }
15048                if (!pkgSetting.getInstalled(userId)) {
15049                    pkgSetting.setInstalled(true, userId);
15050                    pkgSetting.setHidden(false, userId);
15051                    pkgSetting.setInstallReason(installReason, userId);
15052                    mSettings.writePackageRestrictionsLPr(userId);
15053                    mSettings.writeKernelMappingLPr(pkgSetting);
15054                    installed = true;
15055                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15056                    // upgrade app from instant to full; we don't allow app downgrade
15057                    installed = true;
15058                }
15059                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15060            }
15061
15062            if (installed) {
15063                if (pkgSetting.pkg != null) {
15064                    synchronized (mInstallLock) {
15065                        // We don't need to freeze for a brand new install
15066                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15067                    }
15068                }
15069                sendPackageAddedForUser(packageName, pkgSetting, userId);
15070                synchronized (mPackages) {
15071                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15072                }
15073            }
15074        } finally {
15075            Binder.restoreCallingIdentity(callingId);
15076        }
15077
15078        return PackageManager.INSTALL_SUCCEEDED;
15079    }
15080
15081    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15082            boolean instantApp, boolean fullApp) {
15083        // no state specified; do nothing
15084        if (!instantApp && !fullApp) {
15085            return;
15086        }
15087        if (userId != UserHandle.USER_ALL) {
15088            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15089                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15090            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15091                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15092            }
15093        } else {
15094            for (int currentUserId : sUserManager.getUserIds()) {
15095                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15096                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15097                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15098                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15099                }
15100            }
15101        }
15102    }
15103
15104    boolean isUserRestricted(int userId, String restrictionKey) {
15105        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15106        if (restrictions.getBoolean(restrictionKey, false)) {
15107            Log.w(TAG, "User is restricted: " + restrictionKey);
15108            return true;
15109        }
15110        return false;
15111    }
15112
15113    @Override
15114    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15115            int userId) {
15116        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15117        final int callingUid = Binder.getCallingUid();
15118        enforceCrossUserPermission(callingUid, userId,
15119                true /* requireFullPermission */, true /* checkShell */,
15120                "setPackagesSuspended for user " + userId);
15121
15122        if (ArrayUtils.isEmpty(packageNames)) {
15123            return packageNames;
15124        }
15125
15126        // List of package names for whom the suspended state has changed.
15127        List<String> changedPackages = new ArrayList<>(packageNames.length);
15128        // List of package names for whom the suspended state is not set as requested in this
15129        // method.
15130        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15131        long callingId = Binder.clearCallingIdentity();
15132        try {
15133            for (int i = 0; i < packageNames.length; i++) {
15134                String packageName = packageNames[i];
15135                boolean changed = false;
15136                final int appId;
15137                synchronized (mPackages) {
15138                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15139                    if (pkgSetting == null
15140                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15141                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15142                                + "\". Skipping suspending/un-suspending.");
15143                        unactionedPackages.add(packageName);
15144                        continue;
15145                    }
15146                    appId = pkgSetting.appId;
15147                    if (pkgSetting.getSuspended(userId) != suspended) {
15148                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15149                            unactionedPackages.add(packageName);
15150                            continue;
15151                        }
15152                        pkgSetting.setSuspended(suspended, userId);
15153                        mSettings.writePackageRestrictionsLPr(userId);
15154                        changed = true;
15155                        changedPackages.add(packageName);
15156                    }
15157                }
15158
15159                if (changed && suspended) {
15160                    killApplication(packageName, UserHandle.getUid(userId, appId),
15161                            "suspending package");
15162                }
15163            }
15164        } finally {
15165            Binder.restoreCallingIdentity(callingId);
15166        }
15167
15168        if (!changedPackages.isEmpty()) {
15169            sendPackagesSuspendedForUser(changedPackages.toArray(
15170                    new String[changedPackages.size()]), userId, suspended);
15171        }
15172
15173        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15174    }
15175
15176    @Override
15177    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15178        final int callingUid = Binder.getCallingUid();
15179        enforceCrossUserPermission(callingUid, userId,
15180                true /* requireFullPermission */, false /* checkShell */,
15181                "isPackageSuspendedForUser for user " + userId);
15182        synchronized (mPackages) {
15183            final PackageSetting ps = mSettings.mPackages.get(packageName);
15184            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15185                throw new IllegalArgumentException("Unknown target package: " + packageName);
15186            }
15187            return ps.getSuspended(userId);
15188        }
15189    }
15190
15191    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15192        if (isPackageDeviceAdmin(packageName, userId)) {
15193            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15194                    + "\": has an active device admin");
15195            return false;
15196        }
15197
15198        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15199        if (packageName.equals(activeLauncherPackageName)) {
15200            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15201                    + "\": contains the active launcher");
15202            return false;
15203        }
15204
15205        if (packageName.equals(mRequiredInstallerPackage)) {
15206            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15207                    + "\": required for package installation");
15208            return false;
15209        }
15210
15211        if (packageName.equals(mRequiredUninstallerPackage)) {
15212            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15213                    + "\": required for package uninstallation");
15214            return false;
15215        }
15216
15217        if (packageName.equals(mRequiredVerifierPackage)) {
15218            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15219                    + "\": required for package verification");
15220            return false;
15221        }
15222
15223        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15224            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15225                    + "\": is the default dialer");
15226            return false;
15227        }
15228
15229        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15230            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15231                    + "\": protected package");
15232            return false;
15233        }
15234
15235        // Cannot suspend static shared libs as they are considered
15236        // a part of the using app (emulating static linking). Also
15237        // static libs are installed always on internal storage.
15238        PackageParser.Package pkg = mPackages.get(packageName);
15239        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15240            Slog.w(TAG, "Cannot suspend package: " + packageName
15241                    + " providing static shared library: "
15242                    + pkg.staticSharedLibName);
15243            return false;
15244        }
15245
15246        return true;
15247    }
15248
15249    private String getActiveLauncherPackageName(int userId) {
15250        Intent intent = new Intent(Intent.ACTION_MAIN);
15251        intent.addCategory(Intent.CATEGORY_HOME);
15252        ResolveInfo resolveInfo = resolveIntent(
15253                intent,
15254                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15255                PackageManager.MATCH_DEFAULT_ONLY,
15256                userId);
15257
15258        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15259    }
15260
15261    private String getDefaultDialerPackageName(int userId) {
15262        synchronized (mPackages) {
15263            return mSettings.getDefaultDialerPackageNameLPw(userId);
15264        }
15265    }
15266
15267    @Override
15268    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15269        mContext.enforceCallingOrSelfPermission(
15270                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15271                "Only package verification agents can verify applications");
15272
15273        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15274        final PackageVerificationResponse response = new PackageVerificationResponse(
15275                verificationCode, Binder.getCallingUid());
15276        msg.arg1 = id;
15277        msg.obj = response;
15278        mHandler.sendMessage(msg);
15279    }
15280
15281    @Override
15282    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15283            long millisecondsToDelay) {
15284        mContext.enforceCallingOrSelfPermission(
15285                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15286                "Only package verification agents can extend verification timeouts");
15287
15288        final PackageVerificationState state = mPendingVerification.get(id);
15289        final PackageVerificationResponse response = new PackageVerificationResponse(
15290                verificationCodeAtTimeout, Binder.getCallingUid());
15291
15292        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15293            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15294        }
15295        if (millisecondsToDelay < 0) {
15296            millisecondsToDelay = 0;
15297        }
15298        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15299                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15300            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15301        }
15302
15303        if ((state != null) && !state.timeoutExtended()) {
15304            state.extendTimeout();
15305
15306            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15307            msg.arg1 = id;
15308            msg.obj = response;
15309            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15310        }
15311    }
15312
15313    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15314            int verificationCode, UserHandle user) {
15315        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15316        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15317        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15318        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15319        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15320
15321        mContext.sendBroadcastAsUser(intent, user,
15322                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15323    }
15324
15325    private ComponentName matchComponentForVerifier(String packageName,
15326            List<ResolveInfo> receivers) {
15327        ActivityInfo targetReceiver = null;
15328
15329        final int NR = receivers.size();
15330        for (int i = 0; i < NR; i++) {
15331            final ResolveInfo info = receivers.get(i);
15332            if (info.activityInfo == null) {
15333                continue;
15334            }
15335
15336            if (packageName.equals(info.activityInfo.packageName)) {
15337                targetReceiver = info.activityInfo;
15338                break;
15339            }
15340        }
15341
15342        if (targetReceiver == null) {
15343            return null;
15344        }
15345
15346        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15347    }
15348
15349    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15350            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15351        if (pkgInfo.verifiers.length == 0) {
15352            return null;
15353        }
15354
15355        final int N = pkgInfo.verifiers.length;
15356        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15357        for (int i = 0; i < N; i++) {
15358            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15359
15360            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15361                    receivers);
15362            if (comp == null) {
15363                continue;
15364            }
15365
15366            final int verifierUid = getUidForVerifier(verifierInfo);
15367            if (verifierUid == -1) {
15368                continue;
15369            }
15370
15371            if (DEBUG_VERIFY) {
15372                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15373                        + " with the correct signature");
15374            }
15375            sufficientVerifiers.add(comp);
15376            verificationState.addSufficientVerifier(verifierUid);
15377        }
15378
15379        return sufficientVerifiers;
15380    }
15381
15382    private int getUidForVerifier(VerifierInfo verifierInfo) {
15383        synchronized (mPackages) {
15384            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15385            if (pkg == null) {
15386                return -1;
15387            } else if (pkg.mSignatures.length != 1) {
15388                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15389                        + " has more than one signature; ignoring");
15390                return -1;
15391            }
15392
15393            /*
15394             * If the public key of the package's signature does not match
15395             * our expected public key, then this is a different package and
15396             * we should skip.
15397             */
15398
15399            final byte[] expectedPublicKey;
15400            try {
15401                final Signature verifierSig = pkg.mSignatures[0];
15402                final PublicKey publicKey = verifierSig.getPublicKey();
15403                expectedPublicKey = publicKey.getEncoded();
15404            } catch (CertificateException e) {
15405                return -1;
15406            }
15407
15408            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15409
15410            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15411                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15412                        + " does not have the expected public key; ignoring");
15413                return -1;
15414            }
15415
15416            return pkg.applicationInfo.uid;
15417        }
15418    }
15419
15420    @Override
15421    public void finishPackageInstall(int token, boolean didLaunch) {
15422        enforceSystemOrRoot("Only the system is allowed to finish installs");
15423
15424        if (DEBUG_INSTALL) {
15425            Slog.v(TAG, "BM finishing package install for " + token);
15426        }
15427        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15428
15429        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15430        mHandler.sendMessage(msg);
15431    }
15432
15433    /**
15434     * Get the verification agent timeout.  Used for both the APK verifier and the
15435     * intent filter verifier.
15436     *
15437     * @return verification timeout in milliseconds
15438     */
15439    private long getVerificationTimeout() {
15440        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15441                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15442                DEFAULT_VERIFICATION_TIMEOUT);
15443    }
15444
15445    /**
15446     * Get the default verification agent response code.
15447     *
15448     * @return default verification response code
15449     */
15450    private int getDefaultVerificationResponse(UserHandle user) {
15451        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15452            return PackageManager.VERIFICATION_REJECT;
15453        }
15454        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15455                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15456                DEFAULT_VERIFICATION_RESPONSE);
15457    }
15458
15459    /**
15460     * Check whether or not package verification has been enabled.
15461     *
15462     * @return true if verification should be performed
15463     */
15464    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15465        if (!DEFAULT_VERIFY_ENABLE) {
15466            return false;
15467        }
15468
15469        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15470
15471        // Check if installing from ADB
15472        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15473            // Do not run verification in a test harness environment
15474            if (ActivityManager.isRunningInTestHarness()) {
15475                return false;
15476            }
15477            if (ensureVerifyAppsEnabled) {
15478                return true;
15479            }
15480            // Check if the developer does not want package verification for ADB installs
15481            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15482                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15483                return false;
15484            }
15485        } else {
15486            // only when not installed from ADB, skip verification for instant apps when
15487            // the installer and verifier are the same.
15488            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15489                if (mInstantAppInstallerActivity != null
15490                        && mInstantAppInstallerActivity.packageName.equals(
15491                                mRequiredVerifierPackage)) {
15492                    try {
15493                        mContext.getSystemService(AppOpsManager.class)
15494                                .checkPackage(installerUid, mRequiredVerifierPackage);
15495                        if (DEBUG_VERIFY) {
15496                            Slog.i(TAG, "disable verification for instant app");
15497                        }
15498                        return false;
15499                    } catch (SecurityException ignore) { }
15500                }
15501            }
15502        }
15503
15504        if (ensureVerifyAppsEnabled) {
15505            return true;
15506        }
15507
15508        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15509                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15510    }
15511
15512    @Override
15513    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15514            throws RemoteException {
15515        mContext.enforceCallingOrSelfPermission(
15516                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15517                "Only intentfilter verification agents can verify applications");
15518
15519        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15520        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15521                Binder.getCallingUid(), verificationCode, failedDomains);
15522        msg.arg1 = id;
15523        msg.obj = response;
15524        mHandler.sendMessage(msg);
15525    }
15526
15527    @Override
15528    public int getIntentVerificationStatus(String packageName, int userId) {
15529        final int callingUid = Binder.getCallingUid();
15530        if (UserHandle.getUserId(callingUid) != userId) {
15531            mContext.enforceCallingOrSelfPermission(
15532                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15533                    "getIntentVerificationStatus" + userId);
15534        }
15535        if (getInstantAppPackageName(callingUid) != null) {
15536            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15537        }
15538        synchronized (mPackages) {
15539            final PackageSetting ps = mSettings.mPackages.get(packageName);
15540            if (ps == null
15541                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15542                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15543            }
15544            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15545        }
15546    }
15547
15548    @Override
15549    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15550        mContext.enforceCallingOrSelfPermission(
15551                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15552
15553        boolean result = false;
15554        synchronized (mPackages) {
15555            final PackageSetting ps = mSettings.mPackages.get(packageName);
15556            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15557                return false;
15558            }
15559            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15560        }
15561        if (result) {
15562            scheduleWritePackageRestrictionsLocked(userId);
15563        }
15564        return result;
15565    }
15566
15567    @Override
15568    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15569            String packageName) {
15570        final int callingUid = Binder.getCallingUid();
15571        if (getInstantAppPackageName(callingUid) != null) {
15572            return ParceledListSlice.emptyList();
15573        }
15574        synchronized (mPackages) {
15575            final PackageSetting ps = mSettings.mPackages.get(packageName);
15576            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15577                return ParceledListSlice.emptyList();
15578            }
15579            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15580        }
15581    }
15582
15583    @Override
15584    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15585        if (TextUtils.isEmpty(packageName)) {
15586            return ParceledListSlice.emptyList();
15587        }
15588        final int callingUid = Binder.getCallingUid();
15589        final int callingUserId = UserHandle.getUserId(callingUid);
15590        synchronized (mPackages) {
15591            PackageParser.Package pkg = mPackages.get(packageName);
15592            if (pkg == null || pkg.activities == null) {
15593                return ParceledListSlice.emptyList();
15594            }
15595            if (pkg.mExtras == null) {
15596                return ParceledListSlice.emptyList();
15597            }
15598            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15599            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15600                return ParceledListSlice.emptyList();
15601            }
15602            final int count = pkg.activities.size();
15603            ArrayList<IntentFilter> result = new ArrayList<>();
15604            for (int n=0; n<count; n++) {
15605                PackageParser.Activity activity = pkg.activities.get(n);
15606                if (activity.intents != null && activity.intents.size() > 0) {
15607                    result.addAll(activity.intents);
15608                }
15609            }
15610            return new ParceledListSlice<>(result);
15611        }
15612    }
15613
15614    @Override
15615    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15616        mContext.enforceCallingOrSelfPermission(
15617                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15618        if (UserHandle.getCallingUserId() != userId) {
15619            mContext.enforceCallingOrSelfPermission(
15620                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15621        }
15622
15623        synchronized (mPackages) {
15624            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15625            if (packageName != null) {
15626                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15627                        packageName, userId);
15628            }
15629            return result;
15630        }
15631    }
15632
15633    @Override
15634    public String getDefaultBrowserPackageName(int userId) {
15635        if (UserHandle.getCallingUserId() != userId) {
15636            mContext.enforceCallingOrSelfPermission(
15637                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15638        }
15639        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15640            return null;
15641        }
15642        synchronized (mPackages) {
15643            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15644        }
15645    }
15646
15647    /**
15648     * Get the "allow unknown sources" setting.
15649     *
15650     * @return the current "allow unknown sources" setting
15651     */
15652    private int getUnknownSourcesSettings() {
15653        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15654                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15655                -1);
15656    }
15657
15658    @Override
15659    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15660        final int callingUid = Binder.getCallingUid();
15661        if (getInstantAppPackageName(callingUid) != null) {
15662            return;
15663        }
15664        // writer
15665        synchronized (mPackages) {
15666            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15667            if (targetPackageSetting == null
15668                    || filterAppAccessLPr(
15669                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15670                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15671            }
15672
15673            PackageSetting installerPackageSetting;
15674            if (installerPackageName != null) {
15675                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15676                if (installerPackageSetting == null) {
15677                    throw new IllegalArgumentException("Unknown installer package: "
15678                            + installerPackageName);
15679                }
15680            } else {
15681                installerPackageSetting = null;
15682            }
15683
15684            Signature[] callerSignature;
15685            Object obj = mSettings.getUserIdLPr(callingUid);
15686            if (obj != null) {
15687                if (obj instanceof SharedUserSetting) {
15688                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15689                } else if (obj instanceof PackageSetting) {
15690                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15691                } else {
15692                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15693                }
15694            } else {
15695                throw new SecurityException("Unknown calling UID: " + callingUid);
15696            }
15697
15698            // Verify: can't set installerPackageName to a package that is
15699            // not signed with the same cert as the caller.
15700            if (installerPackageSetting != null) {
15701                if (compareSignatures(callerSignature,
15702                        installerPackageSetting.signatures.mSignatures)
15703                        != PackageManager.SIGNATURE_MATCH) {
15704                    throw new SecurityException(
15705                            "Caller does not have same cert as new installer package "
15706                            + installerPackageName);
15707                }
15708            }
15709
15710            // Verify: if target already has an installer package, it must
15711            // be signed with the same cert as the caller.
15712            if (targetPackageSetting.installerPackageName != null) {
15713                PackageSetting setting = mSettings.mPackages.get(
15714                        targetPackageSetting.installerPackageName);
15715                // If the currently set package isn't valid, then it's always
15716                // okay to change it.
15717                if (setting != null) {
15718                    if (compareSignatures(callerSignature,
15719                            setting.signatures.mSignatures)
15720                            != PackageManager.SIGNATURE_MATCH) {
15721                        throw new SecurityException(
15722                                "Caller does not have same cert as old installer package "
15723                                + targetPackageSetting.installerPackageName);
15724                    }
15725                }
15726            }
15727
15728            // Okay!
15729            targetPackageSetting.installerPackageName = installerPackageName;
15730            if (installerPackageName != null) {
15731                mSettings.mInstallerPackages.add(installerPackageName);
15732            }
15733            scheduleWriteSettingsLocked();
15734        }
15735    }
15736
15737    @Override
15738    public void setApplicationCategoryHint(String packageName, int categoryHint,
15739            String callerPackageName) {
15740        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15741            throw new SecurityException("Instant applications don't have access to this method");
15742        }
15743        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15744                callerPackageName);
15745        synchronized (mPackages) {
15746            PackageSetting ps = mSettings.mPackages.get(packageName);
15747            if (ps == null) {
15748                throw new IllegalArgumentException("Unknown target package " + packageName);
15749            }
15750            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15751                throw new IllegalArgumentException("Unknown target package " + packageName);
15752            }
15753            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15754                throw new IllegalArgumentException("Calling package " + callerPackageName
15755                        + " is not installer for " + packageName);
15756            }
15757
15758            if (ps.categoryHint != categoryHint) {
15759                ps.categoryHint = categoryHint;
15760                scheduleWriteSettingsLocked();
15761            }
15762        }
15763    }
15764
15765    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15766        // Queue up an async operation since the package installation may take a little while.
15767        mHandler.post(new Runnable() {
15768            public void run() {
15769                mHandler.removeCallbacks(this);
15770                 // Result object to be returned
15771                PackageInstalledInfo res = new PackageInstalledInfo();
15772                res.setReturnCode(currentStatus);
15773                res.uid = -1;
15774                res.pkg = null;
15775                res.removedInfo = null;
15776                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15777                    args.doPreInstall(res.returnCode);
15778                    synchronized (mInstallLock) {
15779                        installPackageTracedLI(args, res);
15780                    }
15781                    args.doPostInstall(res.returnCode, res.uid);
15782                }
15783
15784                // A restore should be performed at this point if (a) the install
15785                // succeeded, (b) the operation is not an update, and (c) the new
15786                // package has not opted out of backup participation.
15787                final boolean update = res.removedInfo != null
15788                        && res.removedInfo.removedPackage != null;
15789                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15790                boolean doRestore = !update
15791                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15792
15793                // Set up the post-install work request bookkeeping.  This will be used
15794                // and cleaned up by the post-install event handling regardless of whether
15795                // there's a restore pass performed.  Token values are >= 1.
15796                int token;
15797                if (mNextInstallToken < 0) mNextInstallToken = 1;
15798                token = mNextInstallToken++;
15799
15800                PostInstallData data = new PostInstallData(args, res);
15801                mRunningInstalls.put(token, data);
15802                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15803
15804                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15805                    // Pass responsibility to the Backup Manager.  It will perform a
15806                    // restore if appropriate, then pass responsibility back to the
15807                    // Package Manager to run the post-install observer callbacks
15808                    // and broadcasts.
15809                    IBackupManager bm = IBackupManager.Stub.asInterface(
15810                            ServiceManager.getService(Context.BACKUP_SERVICE));
15811                    if (bm != null) {
15812                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15813                                + " to BM for possible restore");
15814                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15815                        try {
15816                            // TODO: http://b/22388012
15817                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15818                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15819                            } else {
15820                                doRestore = false;
15821                            }
15822                        } catch (RemoteException e) {
15823                            // can't happen; the backup manager is local
15824                        } catch (Exception e) {
15825                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15826                            doRestore = false;
15827                        }
15828                    } else {
15829                        Slog.e(TAG, "Backup Manager not found!");
15830                        doRestore = false;
15831                    }
15832                }
15833
15834                if (!doRestore) {
15835                    // No restore possible, or the Backup Manager was mysteriously not
15836                    // available -- just fire the post-install work request directly.
15837                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15838
15839                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15840
15841                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15842                    mHandler.sendMessage(msg);
15843                }
15844            }
15845        });
15846    }
15847
15848    /**
15849     * Callback from PackageSettings whenever an app is first transitioned out of the
15850     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15851     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15852     * here whether the app is the target of an ongoing install, and only send the
15853     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15854     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15855     * handling.
15856     */
15857    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15858        // Serialize this with the rest of the install-process message chain.  In the
15859        // restore-at-install case, this Runnable will necessarily run before the
15860        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15861        // are coherent.  In the non-restore case, the app has already completed install
15862        // and been launched through some other means, so it is not in a problematic
15863        // state for observers to see the FIRST_LAUNCH signal.
15864        mHandler.post(new Runnable() {
15865            @Override
15866            public void run() {
15867                for (int i = 0; i < mRunningInstalls.size(); i++) {
15868                    final PostInstallData data = mRunningInstalls.valueAt(i);
15869                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15870                        continue;
15871                    }
15872                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15873                        // right package; but is it for the right user?
15874                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15875                            if (userId == data.res.newUsers[uIndex]) {
15876                                if (DEBUG_BACKUP) {
15877                                    Slog.i(TAG, "Package " + pkgName
15878                                            + " being restored so deferring FIRST_LAUNCH");
15879                                }
15880                                return;
15881                            }
15882                        }
15883                    }
15884                }
15885                // didn't find it, so not being restored
15886                if (DEBUG_BACKUP) {
15887                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15888                }
15889                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15890            }
15891        });
15892    }
15893
15894    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15895        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15896                installerPkg, null, userIds);
15897    }
15898
15899    private abstract class HandlerParams {
15900        private static final int MAX_RETRIES = 4;
15901
15902        /**
15903         * Number of times startCopy() has been attempted and had a non-fatal
15904         * error.
15905         */
15906        private int mRetries = 0;
15907
15908        /** User handle for the user requesting the information or installation. */
15909        private final UserHandle mUser;
15910        String traceMethod;
15911        int traceCookie;
15912
15913        HandlerParams(UserHandle user) {
15914            mUser = user;
15915        }
15916
15917        UserHandle getUser() {
15918            return mUser;
15919        }
15920
15921        HandlerParams setTraceMethod(String traceMethod) {
15922            this.traceMethod = traceMethod;
15923            return this;
15924        }
15925
15926        HandlerParams setTraceCookie(int traceCookie) {
15927            this.traceCookie = traceCookie;
15928            return this;
15929        }
15930
15931        final boolean startCopy() {
15932            boolean res;
15933            try {
15934                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15935
15936                if (++mRetries > MAX_RETRIES) {
15937                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15938                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15939                    handleServiceError();
15940                    return false;
15941                } else {
15942                    handleStartCopy();
15943                    res = true;
15944                }
15945            } catch (RemoteException e) {
15946                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15947                mHandler.sendEmptyMessage(MCS_RECONNECT);
15948                res = false;
15949            }
15950            handleReturnCode();
15951            return res;
15952        }
15953
15954        final void serviceError() {
15955            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15956            handleServiceError();
15957            handleReturnCode();
15958        }
15959
15960        abstract void handleStartCopy() throws RemoteException;
15961        abstract void handleServiceError();
15962        abstract void handleReturnCode();
15963    }
15964
15965    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15966        for (File path : paths) {
15967            try {
15968                mcs.clearDirectory(path.getAbsolutePath());
15969            } catch (RemoteException e) {
15970            }
15971        }
15972    }
15973
15974    static class OriginInfo {
15975        /**
15976         * Location where install is coming from, before it has been
15977         * copied/renamed into place. This could be a single monolithic APK
15978         * file, or a cluster directory. This location may be untrusted.
15979         */
15980        final File file;
15981        final String cid;
15982
15983        /**
15984         * Flag indicating that {@link #file} or {@link #cid} has already been
15985         * staged, meaning downstream users don't need to defensively copy the
15986         * contents.
15987         */
15988        final boolean staged;
15989
15990        /**
15991         * Flag indicating that {@link #file} or {@link #cid} is an already
15992         * installed app that is being moved.
15993         */
15994        final boolean existing;
15995
15996        final String resolvedPath;
15997        final File resolvedFile;
15998
15999        static OriginInfo fromNothing() {
16000            return new OriginInfo(null, null, false, false);
16001        }
16002
16003        static OriginInfo fromUntrustedFile(File file) {
16004            return new OriginInfo(file, null, false, false);
16005        }
16006
16007        static OriginInfo fromExistingFile(File file) {
16008            return new OriginInfo(file, null, false, true);
16009        }
16010
16011        static OriginInfo fromStagedFile(File file) {
16012            return new OriginInfo(file, null, true, false);
16013        }
16014
16015        static OriginInfo fromStagedContainer(String cid) {
16016            return new OriginInfo(null, cid, true, false);
16017        }
16018
16019        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
16020            this.file = file;
16021            this.cid = cid;
16022            this.staged = staged;
16023            this.existing = existing;
16024
16025            if (cid != null) {
16026                resolvedPath = PackageHelper.getSdDir(cid);
16027                resolvedFile = new File(resolvedPath);
16028            } else if (file != null) {
16029                resolvedPath = file.getAbsolutePath();
16030                resolvedFile = file;
16031            } else {
16032                resolvedPath = null;
16033                resolvedFile = null;
16034            }
16035        }
16036    }
16037
16038    static class MoveInfo {
16039        final int moveId;
16040        final String fromUuid;
16041        final String toUuid;
16042        final String packageName;
16043        final String dataAppName;
16044        final int appId;
16045        final String seinfo;
16046        final int targetSdkVersion;
16047
16048        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16049                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16050            this.moveId = moveId;
16051            this.fromUuid = fromUuid;
16052            this.toUuid = toUuid;
16053            this.packageName = packageName;
16054            this.dataAppName = dataAppName;
16055            this.appId = appId;
16056            this.seinfo = seinfo;
16057            this.targetSdkVersion = targetSdkVersion;
16058        }
16059    }
16060
16061    static class VerificationInfo {
16062        /** A constant used to indicate that a uid value is not present. */
16063        public static final int NO_UID = -1;
16064
16065        /** URI referencing where the package was downloaded from. */
16066        final Uri originatingUri;
16067
16068        /** HTTP referrer URI associated with the originatingURI. */
16069        final Uri referrer;
16070
16071        /** UID of the application that the install request originated from. */
16072        final int originatingUid;
16073
16074        /** UID of application requesting the install */
16075        final int installerUid;
16076
16077        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16078            this.originatingUri = originatingUri;
16079            this.referrer = referrer;
16080            this.originatingUid = originatingUid;
16081            this.installerUid = installerUid;
16082        }
16083    }
16084
16085    class InstallParams extends HandlerParams {
16086        final OriginInfo origin;
16087        final MoveInfo move;
16088        final IPackageInstallObserver2 observer;
16089        int installFlags;
16090        final String installerPackageName;
16091        final String volumeUuid;
16092        private InstallArgs mArgs;
16093        private int mRet;
16094        final String packageAbiOverride;
16095        final String[] grantedRuntimePermissions;
16096        final VerificationInfo verificationInfo;
16097        final Certificate[][] certificates;
16098        final int installReason;
16099
16100        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16101                int installFlags, String installerPackageName, String volumeUuid,
16102                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16103                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16104            super(user);
16105            this.origin = origin;
16106            this.move = move;
16107            this.observer = observer;
16108            this.installFlags = installFlags;
16109            this.installerPackageName = installerPackageName;
16110            this.volumeUuid = volumeUuid;
16111            this.verificationInfo = verificationInfo;
16112            this.packageAbiOverride = packageAbiOverride;
16113            this.grantedRuntimePermissions = grantedPermissions;
16114            this.certificates = certificates;
16115            this.installReason = installReason;
16116        }
16117
16118        @Override
16119        public String toString() {
16120            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16121                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16122        }
16123
16124        private int installLocationPolicy(PackageInfoLite pkgLite) {
16125            String packageName = pkgLite.packageName;
16126            int installLocation = pkgLite.installLocation;
16127            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16128            // reader
16129            synchronized (mPackages) {
16130                // Currently installed package which the new package is attempting to replace or
16131                // null if no such package is installed.
16132                PackageParser.Package installedPkg = mPackages.get(packageName);
16133                // Package which currently owns the data which the new package will own if installed.
16134                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16135                // will be null whereas dataOwnerPkg will contain information about the package
16136                // which was uninstalled while keeping its data.
16137                PackageParser.Package dataOwnerPkg = installedPkg;
16138                if (dataOwnerPkg  == null) {
16139                    PackageSetting ps = mSettings.mPackages.get(packageName);
16140                    if (ps != null) {
16141                        dataOwnerPkg = ps.pkg;
16142                    }
16143                }
16144
16145                if (dataOwnerPkg != null) {
16146                    // If installed, the package will get access to data left on the device by its
16147                    // predecessor. As a security measure, this is permited only if this is not a
16148                    // version downgrade or if the predecessor package is marked as debuggable and
16149                    // a downgrade is explicitly requested.
16150                    //
16151                    // On debuggable platform builds, downgrades are permitted even for
16152                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16153                    // not offer security guarantees and thus it's OK to disable some security
16154                    // mechanisms to make debugging/testing easier on those builds. However, even on
16155                    // debuggable builds downgrades of packages are permitted only if requested via
16156                    // installFlags. This is because we aim to keep the behavior of debuggable
16157                    // platform builds as close as possible to the behavior of non-debuggable
16158                    // platform builds.
16159                    final boolean downgradeRequested =
16160                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16161                    final boolean packageDebuggable =
16162                                (dataOwnerPkg.applicationInfo.flags
16163                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16164                    final boolean downgradePermitted =
16165                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16166                    if (!downgradePermitted) {
16167                        try {
16168                            checkDowngrade(dataOwnerPkg, pkgLite);
16169                        } catch (PackageManagerException e) {
16170                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16171                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16172                        }
16173                    }
16174                }
16175
16176                if (installedPkg != null) {
16177                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16178                        // Check for updated system application.
16179                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16180                            if (onSd) {
16181                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16182                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16183                            }
16184                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16185                        } else {
16186                            if (onSd) {
16187                                // Install flag overrides everything.
16188                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16189                            }
16190                            // If current upgrade specifies particular preference
16191                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16192                                // Application explicitly specified internal.
16193                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16194                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16195                                // App explictly prefers external. Let policy decide
16196                            } else {
16197                                // Prefer previous location
16198                                if (isExternal(installedPkg)) {
16199                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16200                                }
16201                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16202                            }
16203                        }
16204                    } else {
16205                        // Invalid install. Return error code
16206                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16207                    }
16208                }
16209            }
16210            // All the special cases have been taken care of.
16211            // Return result based on recommended install location.
16212            if (onSd) {
16213                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16214            }
16215            return pkgLite.recommendedInstallLocation;
16216        }
16217
16218        /*
16219         * Invoke remote method to get package information and install
16220         * location values. Override install location based on default
16221         * policy if needed and then create install arguments based
16222         * on the install location.
16223         */
16224        public void handleStartCopy() throws RemoteException {
16225            int ret = PackageManager.INSTALL_SUCCEEDED;
16226
16227            // If we're already staged, we've firmly committed to an install location
16228            if (origin.staged) {
16229                if (origin.file != null) {
16230                    installFlags |= PackageManager.INSTALL_INTERNAL;
16231                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16232                } else if (origin.cid != null) {
16233                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16234                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16235                } else {
16236                    throw new IllegalStateException("Invalid stage location");
16237                }
16238            }
16239
16240            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16241            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16242            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16243            PackageInfoLite pkgLite = null;
16244
16245            if (onInt && onSd) {
16246                // Check if both bits are set.
16247                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16248                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16249            } else if (onSd && ephemeral) {
16250                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16251                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16252            } else {
16253                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16254                        packageAbiOverride);
16255
16256                if (DEBUG_EPHEMERAL && ephemeral) {
16257                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16258                }
16259
16260                /*
16261                 * If we have too little free space, try to free cache
16262                 * before giving up.
16263                 */
16264                if (!origin.staged && pkgLite.recommendedInstallLocation
16265                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16266                    // TODO: focus freeing disk space on the target device
16267                    final StorageManager storage = StorageManager.from(mContext);
16268                    final long lowThreshold = storage.getStorageLowBytes(
16269                            Environment.getDataDirectory());
16270
16271                    final long sizeBytes = mContainerService.calculateInstalledSize(
16272                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16273
16274                    try {
16275                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16276                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16277                                installFlags, packageAbiOverride);
16278                    } catch (InstallerException e) {
16279                        Slog.w(TAG, "Failed to free cache", e);
16280                    }
16281
16282                    /*
16283                     * The cache free must have deleted the file we
16284                     * downloaded to install.
16285                     *
16286                     * TODO: fix the "freeCache" call to not delete
16287                     *       the file we care about.
16288                     */
16289                    if (pkgLite.recommendedInstallLocation
16290                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16291                        pkgLite.recommendedInstallLocation
16292                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16293                    }
16294                }
16295            }
16296
16297            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16298                int loc = pkgLite.recommendedInstallLocation;
16299                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16300                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16301                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16302                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16303                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16304                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16305                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16306                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16307                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16308                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16309                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16310                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16311                } else {
16312                    // Override with defaults if needed.
16313                    loc = installLocationPolicy(pkgLite);
16314                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16315                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16316                    } else if (!onSd && !onInt) {
16317                        // Override install location with flags
16318                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16319                            // Set the flag to install on external media.
16320                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16321                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16322                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16323                            if (DEBUG_EPHEMERAL) {
16324                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16325                            }
16326                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16327                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16328                                    |PackageManager.INSTALL_INTERNAL);
16329                        } else {
16330                            // Make sure the flag for installing on external
16331                            // media is unset
16332                            installFlags |= PackageManager.INSTALL_INTERNAL;
16333                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16334                        }
16335                    }
16336                }
16337            }
16338
16339            final InstallArgs args = createInstallArgs(this);
16340            mArgs = args;
16341
16342            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16343                // TODO: http://b/22976637
16344                // Apps installed for "all" users use the device owner to verify the app
16345                UserHandle verifierUser = getUser();
16346                if (verifierUser == UserHandle.ALL) {
16347                    verifierUser = UserHandle.SYSTEM;
16348                }
16349
16350                /*
16351                 * Determine if we have any installed package verifiers. If we
16352                 * do, then we'll defer to them to verify the packages.
16353                 */
16354                final int requiredUid = mRequiredVerifierPackage == null ? -1
16355                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16356                                verifierUser.getIdentifier());
16357                final int installerUid =
16358                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16359                if (!origin.existing && requiredUid != -1
16360                        && isVerificationEnabled(
16361                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16362                    final Intent verification = new Intent(
16363                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16364                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16365                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16366                            PACKAGE_MIME_TYPE);
16367                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16368
16369                    // Query all live verifiers based on current user state
16370                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16371                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16372                            false /*allowDynamicSplits*/);
16373
16374                    if (DEBUG_VERIFY) {
16375                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16376                                + verification.toString() + " with " + pkgLite.verifiers.length
16377                                + " optional verifiers");
16378                    }
16379
16380                    final int verificationId = mPendingVerificationToken++;
16381
16382                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16383
16384                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16385                            installerPackageName);
16386
16387                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16388                            installFlags);
16389
16390                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16391                            pkgLite.packageName);
16392
16393                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16394                            pkgLite.versionCode);
16395
16396                    if (verificationInfo != null) {
16397                        if (verificationInfo.originatingUri != null) {
16398                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16399                                    verificationInfo.originatingUri);
16400                        }
16401                        if (verificationInfo.referrer != null) {
16402                            verification.putExtra(Intent.EXTRA_REFERRER,
16403                                    verificationInfo.referrer);
16404                        }
16405                        if (verificationInfo.originatingUid >= 0) {
16406                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16407                                    verificationInfo.originatingUid);
16408                        }
16409                        if (verificationInfo.installerUid >= 0) {
16410                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16411                                    verificationInfo.installerUid);
16412                        }
16413                    }
16414
16415                    final PackageVerificationState verificationState = new PackageVerificationState(
16416                            requiredUid, args);
16417
16418                    mPendingVerification.append(verificationId, verificationState);
16419
16420                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16421                            receivers, verificationState);
16422
16423                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16424                    final long idleDuration = getVerificationTimeout();
16425
16426                    /*
16427                     * If any sufficient verifiers were listed in the package
16428                     * manifest, attempt to ask them.
16429                     */
16430                    if (sufficientVerifiers != null) {
16431                        final int N = sufficientVerifiers.size();
16432                        if (N == 0) {
16433                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16434                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16435                        } else {
16436                            for (int i = 0; i < N; i++) {
16437                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16438                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16439                                        verifierComponent.getPackageName(), idleDuration,
16440                                        verifierUser.getIdentifier(), false, "package verifier");
16441
16442                                final Intent sufficientIntent = new Intent(verification);
16443                                sufficientIntent.setComponent(verifierComponent);
16444                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16445                            }
16446                        }
16447                    }
16448
16449                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16450                            mRequiredVerifierPackage, receivers);
16451                    if (ret == PackageManager.INSTALL_SUCCEEDED
16452                            && mRequiredVerifierPackage != null) {
16453                        Trace.asyncTraceBegin(
16454                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16455                        /*
16456                         * Send the intent to the required verification agent,
16457                         * but only start the verification timeout after the
16458                         * target BroadcastReceivers have run.
16459                         */
16460                        verification.setComponent(requiredVerifierComponent);
16461                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16462                                mRequiredVerifierPackage, idleDuration,
16463                                verifierUser.getIdentifier(), false, "package verifier");
16464                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16465                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16466                                new BroadcastReceiver() {
16467                                    @Override
16468                                    public void onReceive(Context context, Intent intent) {
16469                                        final Message msg = mHandler
16470                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16471                                        msg.arg1 = verificationId;
16472                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16473                                    }
16474                                }, null, 0, null, null);
16475
16476                        /*
16477                         * We don't want the copy to proceed until verification
16478                         * succeeds, so null out this field.
16479                         */
16480                        mArgs = null;
16481                    }
16482                } else {
16483                    /*
16484                     * No package verification is enabled, so immediately start
16485                     * the remote call to initiate copy using temporary file.
16486                     */
16487                    ret = args.copyApk(mContainerService, true);
16488                }
16489            }
16490
16491            mRet = ret;
16492        }
16493
16494        @Override
16495        void handleReturnCode() {
16496            // If mArgs is null, then MCS couldn't be reached. When it
16497            // reconnects, it will try again to install. At that point, this
16498            // will succeed.
16499            if (mArgs != null) {
16500                processPendingInstall(mArgs, mRet);
16501            }
16502        }
16503
16504        @Override
16505        void handleServiceError() {
16506            mArgs = createInstallArgs(this);
16507            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16508        }
16509
16510        public boolean isForwardLocked() {
16511            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16512        }
16513    }
16514
16515    /**
16516     * Used during creation of InstallArgs
16517     *
16518     * @param installFlags package installation flags
16519     * @return true if should be installed on external storage
16520     */
16521    private static boolean installOnExternalAsec(int installFlags) {
16522        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16523            return false;
16524        }
16525        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16526            return true;
16527        }
16528        return false;
16529    }
16530
16531    /**
16532     * Used during creation of InstallArgs
16533     *
16534     * @param installFlags package installation flags
16535     * @return true if should be installed as forward locked
16536     */
16537    private static boolean installForwardLocked(int installFlags) {
16538        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16539    }
16540
16541    private InstallArgs createInstallArgs(InstallParams params) {
16542        if (params.move != null) {
16543            return new MoveInstallArgs(params);
16544        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16545            return new AsecInstallArgs(params);
16546        } else {
16547            return new FileInstallArgs(params);
16548        }
16549    }
16550
16551    /**
16552     * Create args that describe an existing installed package. Typically used
16553     * when cleaning up old installs, or used as a move source.
16554     */
16555    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16556            String resourcePath, String[] instructionSets) {
16557        final boolean isInAsec;
16558        if (installOnExternalAsec(installFlags)) {
16559            /* Apps on SD card are always in ASEC containers. */
16560            isInAsec = true;
16561        } else if (installForwardLocked(installFlags)
16562                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16563            /*
16564             * Forward-locked apps are only in ASEC containers if they're the
16565             * new style
16566             */
16567            isInAsec = true;
16568        } else {
16569            isInAsec = false;
16570        }
16571
16572        if (isInAsec) {
16573            return new AsecInstallArgs(codePath, instructionSets,
16574                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16575        } else {
16576            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16577        }
16578    }
16579
16580    static abstract class InstallArgs {
16581        /** @see InstallParams#origin */
16582        final OriginInfo origin;
16583        /** @see InstallParams#move */
16584        final MoveInfo move;
16585
16586        final IPackageInstallObserver2 observer;
16587        // Always refers to PackageManager flags only
16588        final int installFlags;
16589        final String installerPackageName;
16590        final String volumeUuid;
16591        final UserHandle user;
16592        final String abiOverride;
16593        final String[] installGrantPermissions;
16594        /** If non-null, drop an async trace when the install completes */
16595        final String traceMethod;
16596        final int traceCookie;
16597        final Certificate[][] certificates;
16598        final int installReason;
16599
16600        // The list of instruction sets supported by this app. This is currently
16601        // only used during the rmdex() phase to clean up resources. We can get rid of this
16602        // if we move dex files under the common app path.
16603        /* nullable */ String[] instructionSets;
16604
16605        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16606                int installFlags, String installerPackageName, String volumeUuid,
16607                UserHandle user, String[] instructionSets,
16608                String abiOverride, String[] installGrantPermissions,
16609                String traceMethod, int traceCookie, Certificate[][] certificates,
16610                int installReason) {
16611            this.origin = origin;
16612            this.move = move;
16613            this.installFlags = installFlags;
16614            this.observer = observer;
16615            this.installerPackageName = installerPackageName;
16616            this.volumeUuid = volumeUuid;
16617            this.user = user;
16618            this.instructionSets = instructionSets;
16619            this.abiOverride = abiOverride;
16620            this.installGrantPermissions = installGrantPermissions;
16621            this.traceMethod = traceMethod;
16622            this.traceCookie = traceCookie;
16623            this.certificates = certificates;
16624            this.installReason = installReason;
16625        }
16626
16627        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16628        abstract int doPreInstall(int status);
16629
16630        /**
16631         * Rename package into final resting place. All paths on the given
16632         * scanned package should be updated to reflect the rename.
16633         */
16634        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16635        abstract int doPostInstall(int status, int uid);
16636
16637        /** @see PackageSettingBase#codePathString */
16638        abstract String getCodePath();
16639        /** @see PackageSettingBase#resourcePathString */
16640        abstract String getResourcePath();
16641
16642        // Need installer lock especially for dex file removal.
16643        abstract void cleanUpResourcesLI();
16644        abstract boolean doPostDeleteLI(boolean delete);
16645
16646        /**
16647         * Called before the source arguments are copied. This is used mostly
16648         * for MoveParams when it needs to read the source file to put it in the
16649         * destination.
16650         */
16651        int doPreCopy() {
16652            return PackageManager.INSTALL_SUCCEEDED;
16653        }
16654
16655        /**
16656         * Called after the source arguments are copied. This is used mostly for
16657         * MoveParams when it needs to read the source file to put it in the
16658         * destination.
16659         */
16660        int doPostCopy(int uid) {
16661            return PackageManager.INSTALL_SUCCEEDED;
16662        }
16663
16664        protected boolean isFwdLocked() {
16665            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16666        }
16667
16668        protected boolean isExternalAsec() {
16669            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16670        }
16671
16672        protected boolean isEphemeral() {
16673            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16674        }
16675
16676        UserHandle getUser() {
16677            return user;
16678        }
16679    }
16680
16681    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16682        if (!allCodePaths.isEmpty()) {
16683            if (instructionSets == null) {
16684                throw new IllegalStateException("instructionSet == null");
16685            }
16686            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16687            for (String codePath : allCodePaths) {
16688                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16689                    try {
16690                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16691                    } catch (InstallerException ignored) {
16692                    }
16693                }
16694            }
16695        }
16696    }
16697
16698    /**
16699     * Logic to handle installation of non-ASEC applications, including copying
16700     * and renaming logic.
16701     */
16702    class FileInstallArgs extends InstallArgs {
16703        private File codeFile;
16704        private File resourceFile;
16705
16706        // Example topology:
16707        // /data/app/com.example/base.apk
16708        // /data/app/com.example/split_foo.apk
16709        // /data/app/com.example/lib/arm/libfoo.so
16710        // /data/app/com.example/lib/arm64/libfoo.so
16711        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16712
16713        /** New install */
16714        FileInstallArgs(InstallParams params) {
16715            super(params.origin, params.move, params.observer, params.installFlags,
16716                    params.installerPackageName, params.volumeUuid,
16717                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16718                    params.grantedRuntimePermissions,
16719                    params.traceMethod, params.traceCookie, params.certificates,
16720                    params.installReason);
16721            if (isFwdLocked()) {
16722                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16723            }
16724        }
16725
16726        /** Existing install */
16727        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16728            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16729                    null, null, null, 0, null /*certificates*/,
16730                    PackageManager.INSTALL_REASON_UNKNOWN);
16731            this.codeFile = (codePath != null) ? new File(codePath) : null;
16732            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16733        }
16734
16735        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16736            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16737            try {
16738                return doCopyApk(imcs, temp);
16739            } finally {
16740                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16741            }
16742        }
16743
16744        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16745            if (origin.staged) {
16746                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16747                codeFile = origin.file;
16748                resourceFile = origin.file;
16749                return PackageManager.INSTALL_SUCCEEDED;
16750            }
16751
16752            try {
16753                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16754                final File tempDir =
16755                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16756                codeFile = tempDir;
16757                resourceFile = tempDir;
16758            } catch (IOException e) {
16759                Slog.w(TAG, "Failed to create copy file: " + e);
16760                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16761            }
16762
16763            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16764                @Override
16765                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16766                    if (!FileUtils.isValidExtFilename(name)) {
16767                        throw new IllegalArgumentException("Invalid filename: " + name);
16768                    }
16769                    try {
16770                        final File file = new File(codeFile, name);
16771                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16772                                O_RDWR | O_CREAT, 0644);
16773                        Os.chmod(file.getAbsolutePath(), 0644);
16774                        return new ParcelFileDescriptor(fd);
16775                    } catch (ErrnoException e) {
16776                        throw new RemoteException("Failed to open: " + e.getMessage());
16777                    }
16778                }
16779            };
16780
16781            int ret = PackageManager.INSTALL_SUCCEEDED;
16782            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16783            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16784                Slog.e(TAG, "Failed to copy package");
16785                return ret;
16786            }
16787
16788            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16789            NativeLibraryHelper.Handle handle = null;
16790            try {
16791                handle = NativeLibraryHelper.Handle.create(codeFile);
16792                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16793                        abiOverride);
16794            } catch (IOException e) {
16795                Slog.e(TAG, "Copying native libraries failed", e);
16796                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16797            } finally {
16798                IoUtils.closeQuietly(handle);
16799            }
16800
16801            return ret;
16802        }
16803
16804        int doPreInstall(int status) {
16805            if (status != PackageManager.INSTALL_SUCCEEDED) {
16806                cleanUp();
16807            }
16808            return status;
16809        }
16810
16811        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16812            if (status != PackageManager.INSTALL_SUCCEEDED) {
16813                cleanUp();
16814                return false;
16815            }
16816
16817            final File targetDir = codeFile.getParentFile();
16818            final File beforeCodeFile = codeFile;
16819            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16820
16821            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16822            try {
16823                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16824            } catch (ErrnoException e) {
16825                Slog.w(TAG, "Failed to rename", e);
16826                return false;
16827            }
16828
16829            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16830                Slog.w(TAG, "Failed to restorecon");
16831                return false;
16832            }
16833
16834            // Reflect the rename internally
16835            codeFile = afterCodeFile;
16836            resourceFile = afterCodeFile;
16837
16838            // Reflect the rename in scanned details
16839            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16840            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16841                    afterCodeFile, pkg.baseCodePath));
16842            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16843                    afterCodeFile, pkg.splitCodePaths));
16844
16845            // Reflect the rename in app info
16846            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16847            pkg.setApplicationInfoCodePath(pkg.codePath);
16848            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16849            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16850            pkg.setApplicationInfoResourcePath(pkg.codePath);
16851            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16852            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16853
16854            return true;
16855        }
16856
16857        int doPostInstall(int status, int uid) {
16858            if (status != PackageManager.INSTALL_SUCCEEDED) {
16859                cleanUp();
16860            }
16861            return status;
16862        }
16863
16864        @Override
16865        String getCodePath() {
16866            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16867        }
16868
16869        @Override
16870        String getResourcePath() {
16871            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16872        }
16873
16874        private boolean cleanUp() {
16875            if (codeFile == null || !codeFile.exists()) {
16876                return false;
16877            }
16878
16879            removeCodePathLI(codeFile);
16880
16881            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16882                resourceFile.delete();
16883            }
16884
16885            return true;
16886        }
16887
16888        void cleanUpResourcesLI() {
16889            // Try enumerating all code paths before deleting
16890            List<String> allCodePaths = Collections.EMPTY_LIST;
16891            if (codeFile != null && codeFile.exists()) {
16892                try {
16893                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16894                    allCodePaths = pkg.getAllCodePaths();
16895                } catch (PackageParserException e) {
16896                    // Ignored; we tried our best
16897                }
16898            }
16899
16900            cleanUp();
16901            removeDexFiles(allCodePaths, instructionSets);
16902        }
16903
16904        boolean doPostDeleteLI(boolean delete) {
16905            // XXX err, shouldn't we respect the delete flag?
16906            cleanUpResourcesLI();
16907            return true;
16908        }
16909    }
16910
16911    private boolean isAsecExternal(String cid) {
16912        final String asecPath = PackageHelper.getSdFilesystem(cid);
16913        return !asecPath.startsWith(mAsecInternalPath);
16914    }
16915
16916    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16917            PackageManagerException {
16918        if (copyRet < 0) {
16919            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16920                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16921                throw new PackageManagerException(copyRet, message);
16922            }
16923        }
16924    }
16925
16926    /**
16927     * Extract the StorageManagerService "container ID" from the full code path of an
16928     * .apk.
16929     */
16930    static String cidFromCodePath(String fullCodePath) {
16931        int eidx = fullCodePath.lastIndexOf("/");
16932        String subStr1 = fullCodePath.substring(0, eidx);
16933        int sidx = subStr1.lastIndexOf("/");
16934        return subStr1.substring(sidx+1, eidx);
16935    }
16936
16937    /**
16938     * Logic to handle installation of ASEC applications, including copying and
16939     * renaming logic.
16940     */
16941    class AsecInstallArgs extends InstallArgs {
16942        static final String RES_FILE_NAME = "pkg.apk";
16943        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16944
16945        String cid;
16946        String packagePath;
16947        String resourcePath;
16948
16949        /** New install */
16950        AsecInstallArgs(InstallParams params) {
16951            super(params.origin, params.move, params.observer, params.installFlags,
16952                    params.installerPackageName, params.volumeUuid,
16953                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16954                    params.grantedRuntimePermissions,
16955                    params.traceMethod, params.traceCookie, params.certificates,
16956                    params.installReason);
16957        }
16958
16959        /** Existing install */
16960        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16961                        boolean isExternal, boolean isForwardLocked) {
16962            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16963                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16964                    instructionSets, null, null, null, 0, null /*certificates*/,
16965                    PackageManager.INSTALL_REASON_UNKNOWN);
16966            // Hackily pretend we're still looking at a full code path
16967            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16968                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16969            }
16970
16971            // Extract cid from fullCodePath
16972            int eidx = fullCodePath.lastIndexOf("/");
16973            String subStr1 = fullCodePath.substring(0, eidx);
16974            int sidx = subStr1.lastIndexOf("/");
16975            cid = subStr1.substring(sidx+1, eidx);
16976            setMountPath(subStr1);
16977        }
16978
16979        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16980            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16981                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16982                    instructionSets, null, null, null, 0, null /*certificates*/,
16983                    PackageManager.INSTALL_REASON_UNKNOWN);
16984            this.cid = cid;
16985            setMountPath(PackageHelper.getSdDir(cid));
16986        }
16987
16988        void createCopyFile() {
16989            cid = mInstallerService.allocateExternalStageCidLegacy();
16990        }
16991
16992        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16993            if (origin.staged && origin.cid != null) {
16994                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16995                cid = origin.cid;
16996                setMountPath(PackageHelper.getSdDir(cid));
16997                return PackageManager.INSTALL_SUCCEEDED;
16998            }
16999
17000            if (temp) {
17001                createCopyFile();
17002            } else {
17003                /*
17004                 * Pre-emptively destroy the container since it's destroyed if
17005                 * copying fails due to it existing anyway.
17006                 */
17007                PackageHelper.destroySdDir(cid);
17008            }
17009
17010            final String newMountPath = imcs.copyPackageToContainer(
17011                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
17012                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
17013
17014            if (newMountPath != null) {
17015                setMountPath(newMountPath);
17016                return PackageManager.INSTALL_SUCCEEDED;
17017            } else {
17018                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17019            }
17020        }
17021
17022        @Override
17023        String getCodePath() {
17024            return packagePath;
17025        }
17026
17027        @Override
17028        String getResourcePath() {
17029            return resourcePath;
17030        }
17031
17032        int doPreInstall(int status) {
17033            if (status != PackageManager.INSTALL_SUCCEEDED) {
17034                // Destroy container
17035                PackageHelper.destroySdDir(cid);
17036            } else {
17037                boolean mounted = PackageHelper.isContainerMounted(cid);
17038                if (!mounted) {
17039                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17040                            Process.SYSTEM_UID);
17041                    if (newMountPath != null) {
17042                        setMountPath(newMountPath);
17043                    } else {
17044                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17045                    }
17046                }
17047            }
17048            return status;
17049        }
17050
17051        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17052            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17053            String newMountPath = null;
17054            if (PackageHelper.isContainerMounted(cid)) {
17055                // Unmount the container
17056                if (!PackageHelper.unMountSdDir(cid)) {
17057                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17058                    return false;
17059                }
17060            }
17061            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17062                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17063                        " which might be stale. Will try to clean up.");
17064                // Clean up the stale container and proceed to recreate.
17065                if (!PackageHelper.destroySdDir(newCacheId)) {
17066                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17067                    return false;
17068                }
17069                // Successfully cleaned up stale container. Try to rename again.
17070                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17071                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17072                            + " inspite of cleaning it up.");
17073                    return false;
17074                }
17075            }
17076            if (!PackageHelper.isContainerMounted(newCacheId)) {
17077                Slog.w(TAG, "Mounting container " + newCacheId);
17078                newMountPath = PackageHelper.mountSdDir(newCacheId,
17079                        getEncryptKey(), Process.SYSTEM_UID);
17080            } else {
17081                newMountPath = PackageHelper.getSdDir(newCacheId);
17082            }
17083            if (newMountPath == null) {
17084                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17085                return false;
17086            }
17087            Log.i(TAG, "Succesfully renamed " + cid +
17088                    " to " + newCacheId +
17089                    " at new path: " + newMountPath);
17090            cid = newCacheId;
17091
17092            final File beforeCodeFile = new File(packagePath);
17093            setMountPath(newMountPath);
17094            final File afterCodeFile = new File(packagePath);
17095
17096            // Reflect the rename in scanned details
17097            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17098            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17099                    afterCodeFile, pkg.baseCodePath));
17100            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17101                    afterCodeFile, pkg.splitCodePaths));
17102
17103            // Reflect the rename in app info
17104            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17105            pkg.setApplicationInfoCodePath(pkg.codePath);
17106            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17107            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17108            pkg.setApplicationInfoResourcePath(pkg.codePath);
17109            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17110            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17111
17112            return true;
17113        }
17114
17115        private void setMountPath(String mountPath) {
17116            final File mountFile = new File(mountPath);
17117
17118            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17119            if (monolithicFile.exists()) {
17120                packagePath = monolithicFile.getAbsolutePath();
17121                if (isFwdLocked()) {
17122                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17123                } else {
17124                    resourcePath = packagePath;
17125                }
17126            } else {
17127                packagePath = mountFile.getAbsolutePath();
17128                resourcePath = packagePath;
17129            }
17130        }
17131
17132        int doPostInstall(int status, int uid) {
17133            if (status != PackageManager.INSTALL_SUCCEEDED) {
17134                cleanUp();
17135            } else {
17136                final int groupOwner;
17137                final String protectedFile;
17138                if (isFwdLocked()) {
17139                    groupOwner = UserHandle.getSharedAppGid(uid);
17140                    protectedFile = RES_FILE_NAME;
17141                } else {
17142                    groupOwner = -1;
17143                    protectedFile = null;
17144                }
17145
17146                if (uid < Process.FIRST_APPLICATION_UID
17147                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17148                    Slog.e(TAG, "Failed to finalize " + cid);
17149                    PackageHelper.destroySdDir(cid);
17150                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17151                }
17152
17153                boolean mounted = PackageHelper.isContainerMounted(cid);
17154                if (!mounted) {
17155                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17156                }
17157            }
17158            return status;
17159        }
17160
17161        private void cleanUp() {
17162            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17163
17164            // Destroy secure container
17165            PackageHelper.destroySdDir(cid);
17166        }
17167
17168        private List<String> getAllCodePaths() {
17169            final File codeFile = new File(getCodePath());
17170            if (codeFile != null && codeFile.exists()) {
17171                try {
17172                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17173                    return pkg.getAllCodePaths();
17174                } catch (PackageParserException e) {
17175                    // Ignored; we tried our best
17176                }
17177            }
17178            return Collections.EMPTY_LIST;
17179        }
17180
17181        void cleanUpResourcesLI() {
17182            // Enumerate all code paths before deleting
17183            cleanUpResourcesLI(getAllCodePaths());
17184        }
17185
17186        private void cleanUpResourcesLI(List<String> allCodePaths) {
17187            cleanUp();
17188            removeDexFiles(allCodePaths, instructionSets);
17189        }
17190
17191        String getPackageName() {
17192            return getAsecPackageName(cid);
17193        }
17194
17195        boolean doPostDeleteLI(boolean delete) {
17196            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17197            final List<String> allCodePaths = getAllCodePaths();
17198            boolean mounted = PackageHelper.isContainerMounted(cid);
17199            if (mounted) {
17200                // Unmount first
17201                if (PackageHelper.unMountSdDir(cid)) {
17202                    mounted = false;
17203                }
17204            }
17205            if (!mounted && delete) {
17206                cleanUpResourcesLI(allCodePaths);
17207            }
17208            return !mounted;
17209        }
17210
17211        @Override
17212        int doPreCopy() {
17213            if (isFwdLocked()) {
17214                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17215                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17216                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17217                }
17218            }
17219
17220            return PackageManager.INSTALL_SUCCEEDED;
17221        }
17222
17223        @Override
17224        int doPostCopy(int uid) {
17225            if (isFwdLocked()) {
17226                if (uid < Process.FIRST_APPLICATION_UID
17227                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17228                                RES_FILE_NAME)) {
17229                    Slog.e(TAG, "Failed to finalize " + cid);
17230                    PackageHelper.destroySdDir(cid);
17231                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17232                }
17233            }
17234
17235            return PackageManager.INSTALL_SUCCEEDED;
17236        }
17237    }
17238
17239    /**
17240     * Logic to handle movement of existing installed applications.
17241     */
17242    class MoveInstallArgs extends InstallArgs {
17243        private File codeFile;
17244        private File resourceFile;
17245
17246        /** New install */
17247        MoveInstallArgs(InstallParams params) {
17248            super(params.origin, params.move, params.observer, params.installFlags,
17249                    params.installerPackageName, params.volumeUuid,
17250                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17251                    params.grantedRuntimePermissions,
17252                    params.traceMethod, params.traceCookie, params.certificates,
17253                    params.installReason);
17254        }
17255
17256        int copyApk(IMediaContainerService imcs, boolean temp) {
17257            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17258                    + move.fromUuid + " to " + move.toUuid);
17259            synchronized (mInstaller) {
17260                try {
17261                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17262                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17263                } catch (InstallerException e) {
17264                    Slog.w(TAG, "Failed to move app", e);
17265                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17266                }
17267            }
17268
17269            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17270            resourceFile = codeFile;
17271            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17272
17273            return PackageManager.INSTALL_SUCCEEDED;
17274        }
17275
17276        int doPreInstall(int status) {
17277            if (status != PackageManager.INSTALL_SUCCEEDED) {
17278                cleanUp(move.toUuid);
17279            }
17280            return status;
17281        }
17282
17283        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17284            if (status != PackageManager.INSTALL_SUCCEEDED) {
17285                cleanUp(move.toUuid);
17286                return false;
17287            }
17288
17289            // Reflect the move in app info
17290            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17291            pkg.setApplicationInfoCodePath(pkg.codePath);
17292            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17293            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17294            pkg.setApplicationInfoResourcePath(pkg.codePath);
17295            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17296            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17297
17298            return true;
17299        }
17300
17301        int doPostInstall(int status, int uid) {
17302            if (status == PackageManager.INSTALL_SUCCEEDED) {
17303                cleanUp(move.fromUuid);
17304            } else {
17305                cleanUp(move.toUuid);
17306            }
17307            return status;
17308        }
17309
17310        @Override
17311        String getCodePath() {
17312            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17313        }
17314
17315        @Override
17316        String getResourcePath() {
17317            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17318        }
17319
17320        private boolean cleanUp(String volumeUuid) {
17321            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17322                    move.dataAppName);
17323            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17324            final int[] userIds = sUserManager.getUserIds();
17325            synchronized (mInstallLock) {
17326                // Clean up both app data and code
17327                // All package moves are frozen until finished
17328                for (int userId : userIds) {
17329                    try {
17330                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17331                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17332                    } catch (InstallerException e) {
17333                        Slog.w(TAG, String.valueOf(e));
17334                    }
17335                }
17336                removeCodePathLI(codeFile);
17337            }
17338            return true;
17339        }
17340
17341        void cleanUpResourcesLI() {
17342            throw new UnsupportedOperationException();
17343        }
17344
17345        boolean doPostDeleteLI(boolean delete) {
17346            throw new UnsupportedOperationException();
17347        }
17348    }
17349
17350    static String getAsecPackageName(String packageCid) {
17351        int idx = packageCid.lastIndexOf("-");
17352        if (idx == -1) {
17353            return packageCid;
17354        }
17355        return packageCid.substring(0, idx);
17356    }
17357
17358    // Utility method used to create code paths based on package name and available index.
17359    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17360        String idxStr = "";
17361        int idx = 1;
17362        // Fall back to default value of idx=1 if prefix is not
17363        // part of oldCodePath
17364        if (oldCodePath != null) {
17365            String subStr = oldCodePath;
17366            // Drop the suffix right away
17367            if (suffix != null && subStr.endsWith(suffix)) {
17368                subStr = subStr.substring(0, subStr.length() - suffix.length());
17369            }
17370            // If oldCodePath already contains prefix find out the
17371            // ending index to either increment or decrement.
17372            int sidx = subStr.lastIndexOf(prefix);
17373            if (sidx != -1) {
17374                subStr = subStr.substring(sidx + prefix.length());
17375                if (subStr != null) {
17376                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17377                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17378                    }
17379                    try {
17380                        idx = Integer.parseInt(subStr);
17381                        if (idx <= 1) {
17382                            idx++;
17383                        } else {
17384                            idx--;
17385                        }
17386                    } catch(NumberFormatException e) {
17387                    }
17388                }
17389            }
17390        }
17391        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17392        return prefix + idxStr;
17393    }
17394
17395    private File getNextCodePath(File targetDir, String packageName) {
17396        File result;
17397        SecureRandom random = new SecureRandom();
17398        byte[] bytes = new byte[16];
17399        do {
17400            random.nextBytes(bytes);
17401            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17402            result = new File(targetDir, packageName + "-" + suffix);
17403        } while (result.exists());
17404        return result;
17405    }
17406
17407    // Utility method that returns the relative package path with respect
17408    // to the installation directory. Like say for /data/data/com.test-1.apk
17409    // string com.test-1 is returned.
17410    static String deriveCodePathName(String codePath) {
17411        if (codePath == null) {
17412            return null;
17413        }
17414        final File codeFile = new File(codePath);
17415        final String name = codeFile.getName();
17416        if (codeFile.isDirectory()) {
17417            return name;
17418        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17419            final int lastDot = name.lastIndexOf('.');
17420            return name.substring(0, lastDot);
17421        } else {
17422            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17423            return null;
17424        }
17425    }
17426
17427    static class PackageInstalledInfo {
17428        String name;
17429        int uid;
17430        // The set of users that originally had this package installed.
17431        int[] origUsers;
17432        // The set of users that now have this package installed.
17433        int[] newUsers;
17434        PackageParser.Package pkg;
17435        int returnCode;
17436        String returnMsg;
17437        String installerPackageName;
17438        PackageRemovedInfo removedInfo;
17439        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17440
17441        public void setError(int code, String msg) {
17442            setReturnCode(code);
17443            setReturnMessage(msg);
17444            Slog.w(TAG, msg);
17445        }
17446
17447        public void setError(String msg, PackageParserException e) {
17448            setReturnCode(e.error);
17449            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17450            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17451            for (int i = 0; i < childCount; i++) {
17452                addedChildPackages.valueAt(i).setError(msg, e);
17453            }
17454            Slog.w(TAG, msg, e);
17455        }
17456
17457        public void setError(String msg, PackageManagerException e) {
17458            returnCode = e.error;
17459            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17460            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17461            for (int i = 0; i < childCount; i++) {
17462                addedChildPackages.valueAt(i).setError(msg, e);
17463            }
17464            Slog.w(TAG, msg, e);
17465        }
17466
17467        public void setReturnCode(int returnCode) {
17468            this.returnCode = returnCode;
17469            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17470            for (int i = 0; i < childCount; i++) {
17471                addedChildPackages.valueAt(i).returnCode = returnCode;
17472            }
17473        }
17474
17475        private void setReturnMessage(String returnMsg) {
17476            this.returnMsg = returnMsg;
17477            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17478            for (int i = 0; i < childCount; i++) {
17479                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17480            }
17481        }
17482
17483        // In some error cases we want to convey more info back to the observer
17484        String origPackage;
17485        String origPermission;
17486    }
17487
17488    /*
17489     * Install a non-existing package.
17490     */
17491    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17492            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17493            PackageInstalledInfo res, int installReason) {
17494        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17495
17496        // Remember this for later, in case we need to rollback this install
17497        String pkgName = pkg.packageName;
17498
17499        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17500
17501        synchronized(mPackages) {
17502            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17503            if (renamedPackage != null) {
17504                // A package with the same name is already installed, though
17505                // it has been renamed to an older name.  The package we
17506                // are trying to install should be installed as an update to
17507                // the existing one, but that has not been requested, so bail.
17508                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17509                        + " without first uninstalling package running as "
17510                        + renamedPackage);
17511                return;
17512            }
17513            if (mPackages.containsKey(pkgName)) {
17514                // Don't allow installation over an existing package with the same name.
17515                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17516                        + " without first uninstalling.");
17517                return;
17518            }
17519        }
17520
17521        try {
17522            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17523                    System.currentTimeMillis(), user);
17524
17525            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17526
17527            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17528                prepareAppDataAfterInstallLIF(newPackage);
17529
17530            } else {
17531                // Remove package from internal structures, but keep around any
17532                // data that might have already existed
17533                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17534                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17535            }
17536        } catch (PackageManagerException e) {
17537            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17538        }
17539
17540        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17541    }
17542
17543    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17544        // Can't rotate keys during boot or if sharedUser.
17545        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17546                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17547            return false;
17548        }
17549        // app is using upgradeKeySets; make sure all are valid
17550        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17551        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17552        for (int i = 0; i < upgradeKeySets.length; i++) {
17553            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17554                Slog.wtf(TAG, "Package "
17555                         + (oldPs.name != null ? oldPs.name : "<null>")
17556                         + " contains upgrade-key-set reference to unknown key-set: "
17557                         + upgradeKeySets[i]
17558                         + " reverting to signatures check.");
17559                return false;
17560            }
17561        }
17562        return true;
17563    }
17564
17565    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17566        // Upgrade keysets are being used.  Determine if new package has a superset of the
17567        // required keys.
17568        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17569        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17570        for (int i = 0; i < upgradeKeySets.length; i++) {
17571            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17572            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17573                return true;
17574            }
17575        }
17576        return false;
17577    }
17578
17579    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17580        try (DigestInputStream digestStream =
17581                new DigestInputStream(new FileInputStream(file), digest)) {
17582            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17583        }
17584    }
17585
17586    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17587            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17588            int installReason) {
17589        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17590
17591        final PackageParser.Package oldPackage;
17592        final PackageSetting ps;
17593        final String pkgName = pkg.packageName;
17594        final int[] allUsers;
17595        final int[] installedUsers;
17596
17597        synchronized(mPackages) {
17598            oldPackage = mPackages.get(pkgName);
17599            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17600
17601            // don't allow upgrade to target a release SDK from a pre-release SDK
17602            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17603                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17604            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17605                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17606            if (oldTargetsPreRelease
17607                    && !newTargetsPreRelease
17608                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17609                Slog.w(TAG, "Can't install package targeting released sdk");
17610                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17611                return;
17612            }
17613
17614            ps = mSettings.mPackages.get(pkgName);
17615
17616            // verify signatures are valid
17617            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17618                if (!checkUpgradeKeySetLP(ps, pkg)) {
17619                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17620                            "New package not signed by keys specified by upgrade-keysets: "
17621                                    + pkgName);
17622                    return;
17623                }
17624            } else {
17625                // default to original signature matching
17626                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17627                        != PackageManager.SIGNATURE_MATCH) {
17628                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17629                            "New package has a different signature: " + pkgName);
17630                    return;
17631                }
17632            }
17633
17634            // don't allow a system upgrade unless the upgrade hash matches
17635            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17636                byte[] digestBytes = null;
17637                try {
17638                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17639                    updateDigest(digest, new File(pkg.baseCodePath));
17640                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17641                        for (String path : pkg.splitCodePaths) {
17642                            updateDigest(digest, new File(path));
17643                        }
17644                    }
17645                    digestBytes = digest.digest();
17646                } catch (NoSuchAlgorithmException | IOException e) {
17647                    res.setError(INSTALL_FAILED_INVALID_APK,
17648                            "Could not compute hash: " + pkgName);
17649                    return;
17650                }
17651                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17652                    res.setError(INSTALL_FAILED_INVALID_APK,
17653                            "New package fails restrict-update check: " + pkgName);
17654                    return;
17655                }
17656                // retain upgrade restriction
17657                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17658            }
17659
17660            // Check for shared user id changes
17661            String invalidPackageName =
17662                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17663            if (invalidPackageName != null) {
17664                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17665                        "Package " + invalidPackageName + " tried to change user "
17666                                + oldPackage.mSharedUserId);
17667                return;
17668            }
17669
17670            // In case of rollback, remember per-user/profile install state
17671            allUsers = sUserManager.getUserIds();
17672            installedUsers = ps.queryInstalledUsers(allUsers, true);
17673
17674            // don't allow an upgrade from full to ephemeral
17675            if (isInstantApp) {
17676                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17677                    for (int currentUser : allUsers) {
17678                        if (!ps.getInstantApp(currentUser)) {
17679                            // can't downgrade from full to instant
17680                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17681                                    + " for user: " + currentUser);
17682                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17683                            return;
17684                        }
17685                    }
17686                } else if (!ps.getInstantApp(user.getIdentifier())) {
17687                    // can't downgrade from full to instant
17688                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17689                            + " for user: " + user.getIdentifier());
17690                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17691                    return;
17692                }
17693            }
17694        }
17695
17696        // Update what is removed
17697        res.removedInfo = new PackageRemovedInfo(this);
17698        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17699        res.removedInfo.removedPackage = oldPackage.packageName;
17700        res.removedInfo.installerPackageName = ps.installerPackageName;
17701        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17702        res.removedInfo.isUpdate = true;
17703        res.removedInfo.origUsers = installedUsers;
17704        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17705        for (int i = 0; i < installedUsers.length; i++) {
17706            final int userId = installedUsers[i];
17707            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17708        }
17709
17710        final int childCount = (oldPackage.childPackages != null)
17711                ? oldPackage.childPackages.size() : 0;
17712        for (int i = 0; i < childCount; i++) {
17713            boolean childPackageUpdated = false;
17714            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17715            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17716            if (res.addedChildPackages != null) {
17717                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17718                if (childRes != null) {
17719                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17720                    childRes.removedInfo.removedPackage = childPkg.packageName;
17721                    if (childPs != null) {
17722                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17723                    }
17724                    childRes.removedInfo.isUpdate = true;
17725                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17726                    childPackageUpdated = true;
17727                }
17728            }
17729            if (!childPackageUpdated) {
17730                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17731                childRemovedRes.removedPackage = childPkg.packageName;
17732                if (childPs != null) {
17733                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17734                }
17735                childRemovedRes.isUpdate = false;
17736                childRemovedRes.dataRemoved = true;
17737                synchronized (mPackages) {
17738                    if (childPs != null) {
17739                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17740                    }
17741                }
17742                if (res.removedInfo.removedChildPackages == null) {
17743                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17744                }
17745                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17746            }
17747        }
17748
17749        boolean sysPkg = (isSystemApp(oldPackage));
17750        if (sysPkg) {
17751            // Set the system/privileged flags as needed
17752            final boolean privileged =
17753                    (oldPackage.applicationInfo.privateFlags
17754                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17755            final int systemPolicyFlags = policyFlags
17756                    | PackageParser.PARSE_IS_SYSTEM
17757                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17758
17759            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17760                    user, allUsers, installerPackageName, res, installReason);
17761        } else {
17762            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17763                    user, allUsers, installerPackageName, res, installReason);
17764        }
17765    }
17766
17767    @Override
17768    public List<String> getPreviousCodePaths(String packageName) {
17769        final int callingUid = Binder.getCallingUid();
17770        final List<String> result = new ArrayList<>();
17771        if (getInstantAppPackageName(callingUid) != null) {
17772            return result;
17773        }
17774        final PackageSetting ps = mSettings.mPackages.get(packageName);
17775        if (ps != null
17776                && ps.oldCodePaths != null
17777                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17778            result.addAll(ps.oldCodePaths);
17779        }
17780        return result;
17781    }
17782
17783    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17784            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17785            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17786            int installReason) {
17787        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17788                + deletedPackage);
17789
17790        String pkgName = deletedPackage.packageName;
17791        boolean deletedPkg = true;
17792        boolean addedPkg = false;
17793        boolean updatedSettings = false;
17794        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17795        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17796                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17797
17798        final long origUpdateTime = (pkg.mExtras != null)
17799                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17800
17801        // First delete the existing package while retaining the data directory
17802        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17803                res.removedInfo, true, pkg)) {
17804            // If the existing package wasn't successfully deleted
17805            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17806            deletedPkg = false;
17807        } else {
17808            // Successfully deleted the old package; proceed with replace.
17809
17810            // If deleted package lived in a container, give users a chance to
17811            // relinquish resources before killing.
17812            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17813                if (DEBUG_INSTALL) {
17814                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17815                }
17816                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17817                final ArrayList<String> pkgList = new ArrayList<String>(1);
17818                pkgList.add(deletedPackage.applicationInfo.packageName);
17819                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17820            }
17821
17822            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17823                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17824            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17825
17826            try {
17827                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17828                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17829                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17830                        installReason);
17831
17832                // Update the in-memory copy of the previous code paths.
17833                PackageSetting ps = mSettings.mPackages.get(pkgName);
17834                if (!killApp) {
17835                    if (ps.oldCodePaths == null) {
17836                        ps.oldCodePaths = new ArraySet<>();
17837                    }
17838                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17839                    if (deletedPackage.splitCodePaths != null) {
17840                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17841                    }
17842                } else {
17843                    ps.oldCodePaths = null;
17844                }
17845                if (ps.childPackageNames != null) {
17846                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17847                        final String childPkgName = ps.childPackageNames.get(i);
17848                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17849                        childPs.oldCodePaths = ps.oldCodePaths;
17850                    }
17851                }
17852                // set instant app status, but, only if it's explicitly specified
17853                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17854                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17855                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17856                prepareAppDataAfterInstallLIF(newPackage);
17857                addedPkg = true;
17858                mDexManager.notifyPackageUpdated(newPackage.packageName,
17859                        newPackage.baseCodePath, newPackage.splitCodePaths);
17860            } catch (PackageManagerException e) {
17861                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17862            }
17863        }
17864
17865        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17866            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17867
17868            // Revert all internal state mutations and added folders for the failed install
17869            if (addedPkg) {
17870                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17871                        res.removedInfo, true, null);
17872            }
17873
17874            // Restore the old package
17875            if (deletedPkg) {
17876                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17877                File restoreFile = new File(deletedPackage.codePath);
17878                // Parse old package
17879                boolean oldExternal = isExternal(deletedPackage);
17880                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17881                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17882                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17883                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17884                try {
17885                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17886                            null);
17887                } catch (PackageManagerException e) {
17888                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17889                            + e.getMessage());
17890                    return;
17891                }
17892
17893                synchronized (mPackages) {
17894                    // Ensure the installer package name up to date
17895                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17896
17897                    // Update permissions for restored package
17898                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17899
17900                    mSettings.writeLPr();
17901                }
17902
17903                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17904            }
17905        } else {
17906            synchronized (mPackages) {
17907                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17908                if (ps != null) {
17909                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17910                    if (res.removedInfo.removedChildPackages != null) {
17911                        final int childCount = res.removedInfo.removedChildPackages.size();
17912                        // Iterate in reverse as we may modify the collection
17913                        for (int i = childCount - 1; i >= 0; i--) {
17914                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17915                            if (res.addedChildPackages.containsKey(childPackageName)) {
17916                                res.removedInfo.removedChildPackages.removeAt(i);
17917                            } else {
17918                                PackageRemovedInfo childInfo = res.removedInfo
17919                                        .removedChildPackages.valueAt(i);
17920                                childInfo.removedForAllUsers = mPackages.get(
17921                                        childInfo.removedPackage) == null;
17922                            }
17923                        }
17924                    }
17925                }
17926            }
17927        }
17928    }
17929
17930    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17931            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17932            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17933            int installReason) {
17934        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17935                + ", old=" + deletedPackage);
17936
17937        final boolean disabledSystem;
17938
17939        // Remove existing system package
17940        removePackageLI(deletedPackage, true);
17941
17942        synchronized (mPackages) {
17943            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17944        }
17945        if (!disabledSystem) {
17946            // We didn't need to disable the .apk as a current system package,
17947            // which means we are replacing another update that is already
17948            // installed.  We need to make sure to delete the older one's .apk.
17949            res.removedInfo.args = createInstallArgsForExisting(0,
17950                    deletedPackage.applicationInfo.getCodePath(),
17951                    deletedPackage.applicationInfo.getResourcePath(),
17952                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17953        } else {
17954            res.removedInfo.args = null;
17955        }
17956
17957        // Successfully disabled the old package. Now proceed with re-installation
17958        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17959                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17960        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17961
17962        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17963        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17964                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17965
17966        PackageParser.Package newPackage = null;
17967        try {
17968            // Add the package to the internal data structures
17969            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17970
17971            // Set the update and install times
17972            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17973            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17974                    System.currentTimeMillis());
17975
17976            // Update the package dynamic state if succeeded
17977            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17978                // Now that the install succeeded make sure we remove data
17979                // directories for any child package the update removed.
17980                final int deletedChildCount = (deletedPackage.childPackages != null)
17981                        ? deletedPackage.childPackages.size() : 0;
17982                final int newChildCount = (newPackage.childPackages != null)
17983                        ? newPackage.childPackages.size() : 0;
17984                for (int i = 0; i < deletedChildCount; i++) {
17985                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17986                    boolean childPackageDeleted = true;
17987                    for (int j = 0; j < newChildCount; j++) {
17988                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17989                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17990                            childPackageDeleted = false;
17991                            break;
17992                        }
17993                    }
17994                    if (childPackageDeleted) {
17995                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17996                                deletedChildPkg.packageName);
17997                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17998                            PackageRemovedInfo removedChildRes = res.removedInfo
17999                                    .removedChildPackages.get(deletedChildPkg.packageName);
18000                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
18001                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
18002                        }
18003                    }
18004                }
18005
18006                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
18007                        installReason);
18008                prepareAppDataAfterInstallLIF(newPackage);
18009
18010                mDexManager.notifyPackageUpdated(newPackage.packageName,
18011                            newPackage.baseCodePath, newPackage.splitCodePaths);
18012            }
18013        } catch (PackageManagerException e) {
18014            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
18015            res.setError("Package couldn't be installed in " + pkg.codePath, e);
18016        }
18017
18018        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
18019            // Re installation failed. Restore old information
18020            // Remove new pkg information
18021            if (newPackage != null) {
18022                removeInstalledPackageLI(newPackage, true);
18023            }
18024            // Add back the old system package
18025            try {
18026                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
18027            } catch (PackageManagerException e) {
18028                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
18029            }
18030
18031            synchronized (mPackages) {
18032                if (disabledSystem) {
18033                    enableSystemPackageLPw(deletedPackage);
18034                }
18035
18036                // Ensure the installer package name up to date
18037                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18038
18039                // Update permissions for restored package
18040                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18041
18042                mSettings.writeLPr();
18043            }
18044
18045            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18046                    + " after failed upgrade");
18047        }
18048    }
18049
18050    /**
18051     * Checks whether the parent or any of the child packages have a change shared
18052     * user. For a package to be a valid update the shred users of the parent and
18053     * the children should match. We may later support changing child shared users.
18054     * @param oldPkg The updated package.
18055     * @param newPkg The update package.
18056     * @return The shared user that change between the versions.
18057     */
18058    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18059            PackageParser.Package newPkg) {
18060        // Check parent shared user
18061        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18062            return newPkg.packageName;
18063        }
18064        // Check child shared users
18065        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18066        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18067        for (int i = 0; i < newChildCount; i++) {
18068            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18069            // If this child was present, did it have the same shared user?
18070            for (int j = 0; j < oldChildCount; j++) {
18071                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18072                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18073                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18074                    return newChildPkg.packageName;
18075                }
18076            }
18077        }
18078        return null;
18079    }
18080
18081    private void removeNativeBinariesLI(PackageSetting ps) {
18082        // Remove the lib path for the parent package
18083        if (ps != null) {
18084            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18085            // Remove the lib path for the child packages
18086            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18087            for (int i = 0; i < childCount; i++) {
18088                PackageSetting childPs = null;
18089                synchronized (mPackages) {
18090                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18091                }
18092                if (childPs != null) {
18093                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18094                            .legacyNativeLibraryPathString);
18095                }
18096            }
18097        }
18098    }
18099
18100    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18101        // Enable the parent package
18102        mSettings.enableSystemPackageLPw(pkg.packageName);
18103        // Enable the child packages
18104        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18105        for (int i = 0; i < childCount; i++) {
18106            PackageParser.Package childPkg = pkg.childPackages.get(i);
18107            mSettings.enableSystemPackageLPw(childPkg.packageName);
18108        }
18109    }
18110
18111    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18112            PackageParser.Package newPkg) {
18113        // Disable the parent package (parent always replaced)
18114        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18115        // Disable the child packages
18116        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18117        for (int i = 0; i < childCount; i++) {
18118            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18119            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18120            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18121        }
18122        return disabled;
18123    }
18124
18125    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18126            String installerPackageName) {
18127        // Enable the parent package
18128        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18129        // Enable the child packages
18130        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18131        for (int i = 0; i < childCount; i++) {
18132            PackageParser.Package childPkg = pkg.childPackages.get(i);
18133            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18134        }
18135    }
18136
18137    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18138        // Collect all used permissions in the UID
18139        ArraySet<String> usedPermissions = new ArraySet<>();
18140        final int packageCount = su.packages.size();
18141        for (int i = 0; i < packageCount; i++) {
18142            PackageSetting ps = su.packages.valueAt(i);
18143            if (ps.pkg == null) {
18144                continue;
18145            }
18146            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18147            for (int j = 0; j < requestedPermCount; j++) {
18148                String permission = ps.pkg.requestedPermissions.get(j);
18149                BasePermission bp = mSettings.mPermissions.get(permission);
18150                if (bp != null) {
18151                    usedPermissions.add(permission);
18152                }
18153            }
18154        }
18155
18156        PermissionsState permissionsState = su.getPermissionsState();
18157        // Prune install permissions
18158        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18159        final int installPermCount = installPermStates.size();
18160        for (int i = installPermCount - 1; i >= 0;  i--) {
18161            PermissionState permissionState = installPermStates.get(i);
18162            if (!usedPermissions.contains(permissionState.getName())) {
18163                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18164                if (bp != null) {
18165                    permissionsState.revokeInstallPermission(bp);
18166                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18167                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18168                }
18169            }
18170        }
18171
18172        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18173
18174        // Prune runtime permissions
18175        for (int userId : allUserIds) {
18176            List<PermissionState> runtimePermStates = permissionsState
18177                    .getRuntimePermissionStates(userId);
18178            final int runtimePermCount = runtimePermStates.size();
18179            for (int i = runtimePermCount - 1; i >= 0; i--) {
18180                PermissionState permissionState = runtimePermStates.get(i);
18181                if (!usedPermissions.contains(permissionState.getName())) {
18182                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18183                    if (bp != null) {
18184                        permissionsState.revokeRuntimePermission(bp, userId);
18185                        permissionsState.updatePermissionFlags(bp, userId,
18186                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18187                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18188                                runtimePermissionChangedUserIds, userId);
18189                    }
18190                }
18191            }
18192        }
18193
18194        return runtimePermissionChangedUserIds;
18195    }
18196
18197    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18198            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18199        // Update the parent package setting
18200        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18201                res, user, installReason);
18202        // Update the child packages setting
18203        final int childCount = (newPackage.childPackages != null)
18204                ? newPackage.childPackages.size() : 0;
18205        for (int i = 0; i < childCount; i++) {
18206            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18207            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18208            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18209                    childRes.origUsers, childRes, user, installReason);
18210        }
18211    }
18212
18213    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18214            String installerPackageName, int[] allUsers, int[] installedForUsers,
18215            PackageInstalledInfo res, UserHandle user, int installReason) {
18216        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18217
18218        String pkgName = newPackage.packageName;
18219        synchronized (mPackages) {
18220            //write settings. the installStatus will be incomplete at this stage.
18221            //note that the new package setting would have already been
18222            //added to mPackages. It hasn't been persisted yet.
18223            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18224            // TODO: Remove this write? It's also written at the end of this method
18225            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18226            mSettings.writeLPr();
18227            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18228        }
18229
18230        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18231        synchronized (mPackages) {
18232            updatePermissionsLPw(newPackage.packageName, newPackage,
18233                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18234                            ? UPDATE_PERMISSIONS_ALL : 0));
18235            // For system-bundled packages, we assume that installing an upgraded version
18236            // of the package implies that the user actually wants to run that new code,
18237            // so we enable the package.
18238            PackageSetting ps = mSettings.mPackages.get(pkgName);
18239            final int userId = user.getIdentifier();
18240            if (ps != null) {
18241                if (isSystemApp(newPackage)) {
18242                    if (DEBUG_INSTALL) {
18243                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18244                    }
18245                    // Enable system package for requested users
18246                    if (res.origUsers != null) {
18247                        for (int origUserId : res.origUsers) {
18248                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18249                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18250                                        origUserId, installerPackageName);
18251                            }
18252                        }
18253                    }
18254                    // Also convey the prior install/uninstall state
18255                    if (allUsers != null && installedForUsers != null) {
18256                        for (int currentUserId : allUsers) {
18257                            final boolean installed = ArrayUtils.contains(
18258                                    installedForUsers, currentUserId);
18259                            if (DEBUG_INSTALL) {
18260                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18261                            }
18262                            ps.setInstalled(installed, currentUserId);
18263                        }
18264                        // these install state changes will be persisted in the
18265                        // upcoming call to mSettings.writeLPr().
18266                    }
18267                }
18268                // It's implied that when a user requests installation, they want the app to be
18269                // installed and enabled.
18270                if (userId != UserHandle.USER_ALL) {
18271                    ps.setInstalled(true, userId);
18272                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18273                }
18274
18275                // When replacing an existing package, preserve the original install reason for all
18276                // users that had the package installed before.
18277                final Set<Integer> previousUserIds = new ArraySet<>();
18278                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18279                    final int installReasonCount = res.removedInfo.installReasons.size();
18280                    for (int i = 0; i < installReasonCount; i++) {
18281                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18282                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18283                        ps.setInstallReason(previousInstallReason, previousUserId);
18284                        previousUserIds.add(previousUserId);
18285                    }
18286                }
18287
18288                // Set install reason for users that are having the package newly installed.
18289                if (userId == UserHandle.USER_ALL) {
18290                    for (int currentUserId : sUserManager.getUserIds()) {
18291                        if (!previousUserIds.contains(currentUserId)) {
18292                            ps.setInstallReason(installReason, currentUserId);
18293                        }
18294                    }
18295                } else if (!previousUserIds.contains(userId)) {
18296                    ps.setInstallReason(installReason, userId);
18297                }
18298                mSettings.writeKernelMappingLPr(ps);
18299            }
18300            res.name = pkgName;
18301            res.uid = newPackage.applicationInfo.uid;
18302            res.pkg = newPackage;
18303            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18304            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18305            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18306            //to update install status
18307            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18308            mSettings.writeLPr();
18309            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18310        }
18311
18312        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18313    }
18314
18315    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18316        try {
18317            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18318            installPackageLI(args, res);
18319        } finally {
18320            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18321        }
18322    }
18323
18324    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18325        final int installFlags = args.installFlags;
18326        final String installerPackageName = args.installerPackageName;
18327        final String volumeUuid = args.volumeUuid;
18328        final File tmpPackageFile = new File(args.getCodePath());
18329        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18330        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18331                || (args.volumeUuid != null));
18332        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18333        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18334        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18335        final boolean virtualPreload =
18336                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18337        boolean replace = false;
18338        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18339        if (args.move != null) {
18340            // moving a complete application; perform an initial scan on the new install location
18341            scanFlags |= SCAN_INITIAL;
18342        }
18343        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18344            scanFlags |= SCAN_DONT_KILL_APP;
18345        }
18346        if (instantApp) {
18347            scanFlags |= SCAN_AS_INSTANT_APP;
18348        }
18349        if (fullApp) {
18350            scanFlags |= SCAN_AS_FULL_APP;
18351        }
18352        if (virtualPreload) {
18353            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18354        }
18355
18356        // Result object to be returned
18357        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18358        res.installerPackageName = installerPackageName;
18359
18360        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18361
18362        // Sanity check
18363        if (instantApp && (forwardLocked || onExternal)) {
18364            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18365                    + " external=" + onExternal);
18366            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18367            return;
18368        }
18369
18370        // Retrieve PackageSettings and parse package
18371        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18372                | PackageParser.PARSE_ENFORCE_CODE
18373                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18374                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18375                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18376                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18377        PackageParser pp = new PackageParser();
18378        pp.setSeparateProcesses(mSeparateProcesses);
18379        pp.setDisplayMetrics(mMetrics);
18380        pp.setCallback(mPackageParserCallback);
18381
18382        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18383        final PackageParser.Package pkg;
18384        try {
18385            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18386        } catch (PackageParserException e) {
18387            res.setError("Failed parse during installPackageLI", e);
18388            return;
18389        } finally {
18390            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18391        }
18392
18393        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18394        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18395            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18396            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18397                    "Instant app package must target O");
18398            return;
18399        }
18400        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18401            Slog.w(TAG, "Instant app package " + pkg.packageName
18402                    + " does not target targetSandboxVersion 2");
18403            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18404                    "Instant app package must use targetSanboxVersion 2");
18405            return;
18406        }
18407
18408        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18409            // Static shared libraries have synthetic package names
18410            renameStaticSharedLibraryPackage(pkg);
18411
18412            // No static shared libs on external storage
18413            if (onExternal) {
18414                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18415                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18416                        "Packages declaring static-shared libs cannot be updated");
18417                return;
18418            }
18419        }
18420
18421        // If we are installing a clustered package add results for the children
18422        if (pkg.childPackages != null) {
18423            synchronized (mPackages) {
18424                final int childCount = pkg.childPackages.size();
18425                for (int i = 0; i < childCount; i++) {
18426                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18427                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18428                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18429                    childRes.pkg = childPkg;
18430                    childRes.name = childPkg.packageName;
18431                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18432                    if (childPs != null) {
18433                        childRes.origUsers = childPs.queryInstalledUsers(
18434                                sUserManager.getUserIds(), true);
18435                    }
18436                    if ((mPackages.containsKey(childPkg.packageName))) {
18437                        childRes.removedInfo = new PackageRemovedInfo(this);
18438                        childRes.removedInfo.removedPackage = childPkg.packageName;
18439                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18440                    }
18441                    if (res.addedChildPackages == null) {
18442                        res.addedChildPackages = new ArrayMap<>();
18443                    }
18444                    res.addedChildPackages.put(childPkg.packageName, childRes);
18445                }
18446            }
18447        }
18448
18449        // If package doesn't declare API override, mark that we have an install
18450        // time CPU ABI override.
18451        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18452            pkg.cpuAbiOverride = args.abiOverride;
18453        }
18454
18455        String pkgName = res.name = pkg.packageName;
18456        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18457            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18458                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18459                return;
18460            }
18461        }
18462
18463        try {
18464            // either use what we've been given or parse directly from the APK
18465            if (args.certificates != null) {
18466                try {
18467                    PackageParser.populateCertificates(pkg, args.certificates);
18468                } catch (PackageParserException e) {
18469                    // there was something wrong with the certificates we were given;
18470                    // try to pull them from the APK
18471                    PackageParser.collectCertificates(pkg, parseFlags);
18472                }
18473            } else {
18474                PackageParser.collectCertificates(pkg, parseFlags);
18475            }
18476        } catch (PackageParserException e) {
18477            res.setError("Failed collect during installPackageLI", e);
18478            return;
18479        }
18480
18481        // Get rid of all references to package scan path via parser.
18482        pp = null;
18483        String oldCodePath = null;
18484        boolean systemApp = false;
18485        synchronized (mPackages) {
18486            // Check if installing already existing package
18487            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18488                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18489                if (pkg.mOriginalPackages != null
18490                        && pkg.mOriginalPackages.contains(oldName)
18491                        && mPackages.containsKey(oldName)) {
18492                    // This package is derived from an original package,
18493                    // and this device has been updating from that original
18494                    // name.  We must continue using the original name, so
18495                    // rename the new package here.
18496                    pkg.setPackageName(oldName);
18497                    pkgName = pkg.packageName;
18498                    replace = true;
18499                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18500                            + oldName + " pkgName=" + pkgName);
18501                } else if (mPackages.containsKey(pkgName)) {
18502                    // This package, under its official name, already exists
18503                    // on the device; we should replace it.
18504                    replace = true;
18505                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18506                }
18507
18508                // Child packages are installed through the parent package
18509                if (pkg.parentPackage != null) {
18510                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18511                            "Package " + pkg.packageName + " is child of package "
18512                                    + pkg.parentPackage.parentPackage + ". Child packages "
18513                                    + "can be updated only through the parent package.");
18514                    return;
18515                }
18516
18517                if (replace) {
18518                    // Prevent apps opting out from runtime permissions
18519                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18520                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18521                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18522                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18523                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18524                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18525                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18526                                        + " doesn't support runtime permissions but the old"
18527                                        + " target SDK " + oldTargetSdk + " does.");
18528                        return;
18529                    }
18530                    // Prevent apps from downgrading their targetSandbox.
18531                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18532                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18533                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18534                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18535                                "Package " + pkg.packageName + " new target sandbox "
18536                                + newTargetSandbox + " is incompatible with the previous value of"
18537                                + oldTargetSandbox + ".");
18538                        return;
18539                    }
18540
18541                    // Prevent installing of child packages
18542                    if (oldPackage.parentPackage != null) {
18543                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18544                                "Package " + pkg.packageName + " is child of package "
18545                                        + oldPackage.parentPackage + ". Child packages "
18546                                        + "can be updated only through the parent package.");
18547                        return;
18548                    }
18549                }
18550            }
18551
18552            PackageSetting ps = mSettings.mPackages.get(pkgName);
18553            if (ps != null) {
18554                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18555
18556                // Static shared libs have same package with different versions where
18557                // we internally use a synthetic package name to allow multiple versions
18558                // of the same package, therefore we need to compare signatures against
18559                // the package setting for the latest library version.
18560                PackageSetting signatureCheckPs = ps;
18561                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18562                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18563                    if (libraryEntry != null) {
18564                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18565                    }
18566                }
18567
18568                // Quick sanity check that we're signed correctly if updating;
18569                // we'll check this again later when scanning, but we want to
18570                // bail early here before tripping over redefined permissions.
18571                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18572                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18573                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18574                                + pkg.packageName + " upgrade keys do not match the "
18575                                + "previously installed version");
18576                        return;
18577                    }
18578                } else {
18579                    try {
18580                        verifySignaturesLP(signatureCheckPs, pkg);
18581                    } catch (PackageManagerException e) {
18582                        res.setError(e.error, e.getMessage());
18583                        return;
18584                    }
18585                }
18586
18587                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18588                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18589                    systemApp = (ps.pkg.applicationInfo.flags &
18590                            ApplicationInfo.FLAG_SYSTEM) != 0;
18591                }
18592                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18593            }
18594
18595            int N = pkg.permissions.size();
18596            for (int i = N-1; i >= 0; i--) {
18597                PackageParser.Permission perm = pkg.permissions.get(i);
18598                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18599
18600                // Don't allow anyone but the system to define ephemeral permissions.
18601                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18602                        && !systemApp) {
18603                    Slog.w(TAG, "Non-System package " + pkg.packageName
18604                            + " attempting to delcare ephemeral permission "
18605                            + perm.info.name + "; Removing ephemeral.");
18606                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18607                }
18608                // Check whether the newly-scanned package wants to define an already-defined perm
18609                if (bp != null) {
18610                    // If the defining package is signed with our cert, it's okay.  This
18611                    // also includes the "updating the same package" case, of course.
18612                    // "updating same package" could also involve key-rotation.
18613                    final boolean sigsOk;
18614                    if (bp.sourcePackage.equals(pkg.packageName)
18615                            && (bp.packageSetting instanceof PackageSetting)
18616                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18617                                    scanFlags))) {
18618                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18619                    } else {
18620                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18621                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18622                    }
18623                    if (!sigsOk) {
18624                        // If the owning package is the system itself, we log but allow
18625                        // install to proceed; we fail the install on all other permission
18626                        // redefinitions.
18627                        if (!bp.sourcePackage.equals("android")) {
18628                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18629                                    + pkg.packageName + " attempting to redeclare permission "
18630                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18631                            res.origPermission = perm.info.name;
18632                            res.origPackage = bp.sourcePackage;
18633                            return;
18634                        } else {
18635                            Slog.w(TAG, "Package " + pkg.packageName
18636                                    + " attempting to redeclare system permission "
18637                                    + perm.info.name + "; ignoring new declaration");
18638                            pkg.permissions.remove(i);
18639                        }
18640                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18641                        // Prevent apps to change protection level to dangerous from any other
18642                        // type as this would allow a privilege escalation where an app adds a
18643                        // normal/signature permission in other app's group and later redefines
18644                        // it as dangerous leading to the group auto-grant.
18645                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18646                                == PermissionInfo.PROTECTION_DANGEROUS) {
18647                            if (bp != null && !bp.isRuntime()) {
18648                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18649                                        + "non-runtime permission " + perm.info.name
18650                                        + " to runtime; keeping old protection level");
18651                                perm.info.protectionLevel = bp.protectionLevel;
18652                            }
18653                        }
18654                    }
18655                }
18656            }
18657        }
18658
18659        if (systemApp) {
18660            if (onExternal) {
18661                // Abort update; system app can't be replaced with app on sdcard
18662                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18663                        "Cannot install updates to system apps on sdcard");
18664                return;
18665            } else if (instantApp) {
18666                // Abort update; system app can't be replaced with an instant app
18667                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18668                        "Cannot update a system app with an instant app");
18669                return;
18670            }
18671        }
18672
18673        if (args.move != null) {
18674            // We did an in-place move, so dex is ready to roll
18675            scanFlags |= SCAN_NO_DEX;
18676            scanFlags |= SCAN_MOVE;
18677
18678            synchronized (mPackages) {
18679                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18680                if (ps == null) {
18681                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18682                            "Missing settings for moved package " + pkgName);
18683                }
18684
18685                // We moved the entire application as-is, so bring over the
18686                // previously derived ABI information.
18687                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18688                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18689            }
18690
18691        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18692            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18693            scanFlags |= SCAN_NO_DEX;
18694
18695            try {
18696                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18697                    args.abiOverride : pkg.cpuAbiOverride);
18698                final boolean extractNativeLibs = !pkg.isLibrary();
18699                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18700                        extractNativeLibs, mAppLib32InstallDir);
18701            } catch (PackageManagerException pme) {
18702                Slog.e(TAG, "Error deriving application ABI", pme);
18703                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18704                return;
18705            }
18706
18707            // Shared libraries for the package need to be updated.
18708            synchronized (mPackages) {
18709                try {
18710                    updateSharedLibrariesLPr(pkg, null);
18711                } catch (PackageManagerException e) {
18712                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18713                }
18714            }
18715        }
18716
18717        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18718            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18719            return;
18720        }
18721
18722        // Verify if we need to dexopt the app.
18723        //
18724        // NOTE: it is *important* to call dexopt after doRename which will sync the
18725        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18726        //
18727        // We only need to dexopt if the package meets ALL of the following conditions:
18728        //   1) it is not forward locked.
18729        //   2) it is not on on an external ASEC container.
18730        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18731        //
18732        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18733        // complete, so we skip this step during installation. Instead, we'll take extra time
18734        // the first time the instant app starts. It's preferred to do it this way to provide
18735        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18736        // middle of running an instant app. The default behaviour can be overridden
18737        // via gservices.
18738        final boolean performDexopt = !forwardLocked
18739            && !pkg.applicationInfo.isExternalAsec()
18740            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18741                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18742
18743        if (performDexopt) {
18744            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18745            // Do not run PackageDexOptimizer through the local performDexOpt
18746            // method because `pkg` may not be in `mPackages` yet.
18747            //
18748            // Also, don't fail application installs if the dexopt step fails.
18749            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18750                REASON_INSTALL,
18751                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18752            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18753                null /* instructionSets */,
18754                getOrCreateCompilerPackageStats(pkg),
18755                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18756                dexoptOptions);
18757            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18758        }
18759
18760        // Notify BackgroundDexOptService that the package has been changed.
18761        // If this is an update of a package which used to fail to compile,
18762        // BackgroundDexOptService will remove it from its blacklist.
18763        // TODO: Layering violation
18764        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18765
18766        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18767
18768        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18769                "installPackageLI")) {
18770            if (replace) {
18771                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18772                    // Static libs have a synthetic package name containing the version
18773                    // and cannot be updated as an update would get a new package name,
18774                    // unless this is the exact same version code which is useful for
18775                    // development.
18776                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18777                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18778                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18779                                + "static-shared libs cannot be updated");
18780                        return;
18781                    }
18782                }
18783                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18784                        installerPackageName, res, args.installReason);
18785            } else {
18786                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18787                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18788            }
18789        }
18790
18791        synchronized (mPackages) {
18792            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18793            if (ps != null) {
18794                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18795                ps.setUpdateAvailable(false /*updateAvailable*/);
18796            }
18797
18798            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18799            for (int i = 0; i < childCount; i++) {
18800                PackageParser.Package childPkg = pkg.childPackages.get(i);
18801                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18802                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18803                if (childPs != null) {
18804                    childRes.newUsers = childPs.queryInstalledUsers(
18805                            sUserManager.getUserIds(), true);
18806                }
18807            }
18808
18809            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18810                updateSequenceNumberLP(ps, res.newUsers);
18811                updateInstantAppInstallerLocked(pkgName);
18812            }
18813        }
18814    }
18815
18816    private void startIntentFilterVerifications(int userId, boolean replacing,
18817            PackageParser.Package pkg) {
18818        if (mIntentFilterVerifierComponent == null) {
18819            Slog.w(TAG, "No IntentFilter verification will not be done as "
18820                    + "there is no IntentFilterVerifier available!");
18821            return;
18822        }
18823
18824        final int verifierUid = getPackageUid(
18825                mIntentFilterVerifierComponent.getPackageName(),
18826                MATCH_DEBUG_TRIAGED_MISSING,
18827                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18828
18829        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18830        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18831        mHandler.sendMessage(msg);
18832
18833        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18834        for (int i = 0; i < childCount; i++) {
18835            PackageParser.Package childPkg = pkg.childPackages.get(i);
18836            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18837            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18838            mHandler.sendMessage(msg);
18839        }
18840    }
18841
18842    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18843            PackageParser.Package pkg) {
18844        int size = pkg.activities.size();
18845        if (size == 0) {
18846            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18847                    "No activity, so no need to verify any IntentFilter!");
18848            return;
18849        }
18850
18851        final boolean hasDomainURLs = hasDomainURLs(pkg);
18852        if (!hasDomainURLs) {
18853            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18854                    "No domain URLs, so no need to verify any IntentFilter!");
18855            return;
18856        }
18857
18858        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18859                + " if any IntentFilter from the " + size
18860                + " Activities needs verification ...");
18861
18862        int count = 0;
18863        final String packageName = pkg.packageName;
18864
18865        synchronized (mPackages) {
18866            // If this is a new install and we see that we've already run verification for this
18867            // package, we have nothing to do: it means the state was restored from backup.
18868            if (!replacing) {
18869                IntentFilterVerificationInfo ivi =
18870                        mSettings.getIntentFilterVerificationLPr(packageName);
18871                if (ivi != null) {
18872                    if (DEBUG_DOMAIN_VERIFICATION) {
18873                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18874                                + ivi.getStatusString());
18875                    }
18876                    return;
18877                }
18878            }
18879
18880            // If any filters need to be verified, then all need to be.
18881            boolean needToVerify = false;
18882            for (PackageParser.Activity a : pkg.activities) {
18883                for (ActivityIntentInfo filter : a.intents) {
18884                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18885                        if (DEBUG_DOMAIN_VERIFICATION) {
18886                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18887                        }
18888                        needToVerify = true;
18889                        break;
18890                    }
18891                }
18892            }
18893
18894            if (needToVerify) {
18895                final int verificationId = mIntentFilterVerificationToken++;
18896                for (PackageParser.Activity a : pkg.activities) {
18897                    for (ActivityIntentInfo filter : a.intents) {
18898                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18899                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18900                                    "Verification needed for IntentFilter:" + filter.toString());
18901                            mIntentFilterVerifier.addOneIntentFilterVerification(
18902                                    verifierUid, userId, verificationId, filter, packageName);
18903                            count++;
18904                        }
18905                    }
18906                }
18907            }
18908        }
18909
18910        if (count > 0) {
18911            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18912                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18913                    +  " for userId:" + userId);
18914            mIntentFilterVerifier.startVerifications(userId);
18915        } else {
18916            if (DEBUG_DOMAIN_VERIFICATION) {
18917                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18918            }
18919        }
18920    }
18921
18922    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18923        final ComponentName cn  = filter.activity.getComponentName();
18924        final String packageName = cn.getPackageName();
18925
18926        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18927                packageName);
18928        if (ivi == null) {
18929            return true;
18930        }
18931        int status = ivi.getStatus();
18932        switch (status) {
18933            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18934            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18935                return true;
18936
18937            default:
18938                // Nothing to do
18939                return false;
18940        }
18941    }
18942
18943    private static boolean isMultiArch(ApplicationInfo info) {
18944        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18945    }
18946
18947    private static boolean isExternal(PackageParser.Package pkg) {
18948        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18949    }
18950
18951    private static boolean isExternal(PackageSetting ps) {
18952        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18953    }
18954
18955    private static boolean isSystemApp(PackageParser.Package pkg) {
18956        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18957    }
18958
18959    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18960        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18961    }
18962
18963    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18964        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18965    }
18966
18967    private static boolean isSystemApp(PackageSetting ps) {
18968        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18969    }
18970
18971    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18972        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18973    }
18974
18975    private int packageFlagsToInstallFlags(PackageSetting ps) {
18976        int installFlags = 0;
18977        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18978            // This existing package was an external ASEC install when we have
18979            // the external flag without a UUID
18980            installFlags |= PackageManager.INSTALL_EXTERNAL;
18981        }
18982        if (ps.isForwardLocked()) {
18983            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18984        }
18985        return installFlags;
18986    }
18987
18988    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18989        if (isExternal(pkg)) {
18990            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18991                return StorageManager.UUID_PRIMARY_PHYSICAL;
18992            } else {
18993                return pkg.volumeUuid;
18994            }
18995        } else {
18996            return StorageManager.UUID_PRIVATE_INTERNAL;
18997        }
18998    }
18999
19000    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
19001        if (isExternal(pkg)) {
19002            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19003                return mSettings.getExternalVersion();
19004            } else {
19005                return mSettings.findOrCreateVersion(pkg.volumeUuid);
19006            }
19007        } else {
19008            return mSettings.getInternalVersion();
19009        }
19010    }
19011
19012    private void deleteTempPackageFiles() {
19013        final FilenameFilter filter = new FilenameFilter() {
19014            public boolean accept(File dir, String name) {
19015                return name.startsWith("vmdl") && name.endsWith(".tmp");
19016            }
19017        };
19018        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
19019            file.delete();
19020        }
19021    }
19022
19023    @Override
19024    public void deletePackageAsUser(String packageName, int versionCode,
19025            IPackageDeleteObserver observer, int userId, int flags) {
19026        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
19027                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
19028    }
19029
19030    @Override
19031    public void deletePackageVersioned(VersionedPackage versionedPackage,
19032            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
19033        final int callingUid = Binder.getCallingUid();
19034        mContext.enforceCallingOrSelfPermission(
19035                android.Manifest.permission.DELETE_PACKAGES, null);
19036        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
19037        Preconditions.checkNotNull(versionedPackage);
19038        Preconditions.checkNotNull(observer);
19039        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
19040                PackageManager.VERSION_CODE_HIGHEST,
19041                Integer.MAX_VALUE, "versionCode must be >= -1");
19042
19043        final String packageName = versionedPackage.getPackageName();
19044        final int versionCode = versionedPackage.getVersionCode();
19045        final String internalPackageName;
19046        synchronized (mPackages) {
19047            // Normalize package name to handle renamed packages and static libs
19048            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19049                    versionedPackage.getVersionCode());
19050        }
19051
19052        final int uid = Binder.getCallingUid();
19053        if (!isOrphaned(internalPackageName)
19054                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19055            try {
19056                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19057                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19058                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19059                observer.onUserActionRequired(intent);
19060            } catch (RemoteException re) {
19061            }
19062            return;
19063        }
19064        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19065        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19066        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19067            mContext.enforceCallingOrSelfPermission(
19068                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19069                    "deletePackage for user " + userId);
19070        }
19071
19072        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19073            try {
19074                observer.onPackageDeleted(packageName,
19075                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19076            } catch (RemoteException re) {
19077            }
19078            return;
19079        }
19080
19081        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19082            try {
19083                observer.onPackageDeleted(packageName,
19084                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19085            } catch (RemoteException re) {
19086            }
19087            return;
19088        }
19089
19090        if (DEBUG_REMOVE) {
19091            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19092                    + " deleteAllUsers: " + deleteAllUsers + " version="
19093                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19094                    ? "VERSION_CODE_HIGHEST" : versionCode));
19095        }
19096        // Queue up an async operation since the package deletion may take a little while.
19097        mHandler.post(new Runnable() {
19098            public void run() {
19099                mHandler.removeCallbacks(this);
19100                int returnCode;
19101                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19102                boolean doDeletePackage = true;
19103                if (ps != null) {
19104                    final boolean targetIsInstantApp =
19105                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19106                    doDeletePackage = !targetIsInstantApp
19107                            || canViewInstantApps;
19108                }
19109                if (doDeletePackage) {
19110                    if (!deleteAllUsers) {
19111                        returnCode = deletePackageX(internalPackageName, versionCode,
19112                                userId, deleteFlags);
19113                    } else {
19114                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19115                                internalPackageName, users);
19116                        // If nobody is blocking uninstall, proceed with delete for all users
19117                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19118                            returnCode = deletePackageX(internalPackageName, versionCode,
19119                                    userId, deleteFlags);
19120                        } else {
19121                            // Otherwise uninstall individually for users with blockUninstalls=false
19122                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19123                            for (int userId : users) {
19124                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19125                                    returnCode = deletePackageX(internalPackageName, versionCode,
19126                                            userId, userFlags);
19127                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19128                                        Slog.w(TAG, "Package delete failed for user " + userId
19129                                                + ", returnCode " + returnCode);
19130                                    }
19131                                }
19132                            }
19133                            // The app has only been marked uninstalled for certain users.
19134                            // We still need to report that delete was blocked
19135                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19136                        }
19137                    }
19138                } else {
19139                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19140                }
19141                try {
19142                    observer.onPackageDeleted(packageName, returnCode, null);
19143                } catch (RemoteException e) {
19144                    Log.i(TAG, "Observer no longer exists.");
19145                } //end catch
19146            } //end run
19147        });
19148    }
19149
19150    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19151        if (pkg.staticSharedLibName != null) {
19152            return pkg.manifestPackageName;
19153        }
19154        return pkg.packageName;
19155    }
19156
19157    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19158        // Handle renamed packages
19159        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19160        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19161
19162        // Is this a static library?
19163        SparseArray<SharedLibraryEntry> versionedLib =
19164                mStaticLibsByDeclaringPackage.get(packageName);
19165        if (versionedLib == null || versionedLib.size() <= 0) {
19166            return packageName;
19167        }
19168
19169        // Figure out which lib versions the caller can see
19170        SparseIntArray versionsCallerCanSee = null;
19171        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19172        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19173                && callingAppId != Process.ROOT_UID) {
19174            versionsCallerCanSee = new SparseIntArray();
19175            String libName = versionedLib.valueAt(0).info.getName();
19176            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19177            if (uidPackages != null) {
19178                for (String uidPackage : uidPackages) {
19179                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19180                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19181                    if (libIdx >= 0) {
19182                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19183                        versionsCallerCanSee.append(libVersion, libVersion);
19184                    }
19185                }
19186            }
19187        }
19188
19189        // Caller can see nothing - done
19190        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19191            return packageName;
19192        }
19193
19194        // Find the version the caller can see and the app version code
19195        SharedLibraryEntry highestVersion = null;
19196        final int versionCount = versionedLib.size();
19197        for (int i = 0; i < versionCount; i++) {
19198            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19199            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19200                    libEntry.info.getVersion()) < 0) {
19201                continue;
19202            }
19203            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19204            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19205                if (libVersionCode == versionCode) {
19206                    return libEntry.apk;
19207                }
19208            } else if (highestVersion == null) {
19209                highestVersion = libEntry;
19210            } else if (libVersionCode  > highestVersion.info
19211                    .getDeclaringPackage().getVersionCode()) {
19212                highestVersion = libEntry;
19213            }
19214        }
19215
19216        if (highestVersion != null) {
19217            return highestVersion.apk;
19218        }
19219
19220        return packageName;
19221    }
19222
19223    boolean isCallerVerifier(int callingUid) {
19224        final int callingUserId = UserHandle.getUserId(callingUid);
19225        return mRequiredVerifierPackage != null &&
19226                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19227    }
19228
19229    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19230        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19231              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19232            return true;
19233        }
19234        final int callingUserId = UserHandle.getUserId(callingUid);
19235        // If the caller installed the pkgName, then allow it to silently uninstall.
19236        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19237            return true;
19238        }
19239
19240        // Allow package verifier to silently uninstall.
19241        if (mRequiredVerifierPackage != null &&
19242                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19243            return true;
19244        }
19245
19246        // Allow package uninstaller to silently uninstall.
19247        if (mRequiredUninstallerPackage != null &&
19248                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19249            return true;
19250        }
19251
19252        // Allow storage manager to silently uninstall.
19253        if (mStorageManagerPackage != null &&
19254                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19255            return true;
19256        }
19257
19258        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19259        // uninstall for device owner provisioning.
19260        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19261                == PERMISSION_GRANTED) {
19262            return true;
19263        }
19264
19265        return false;
19266    }
19267
19268    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19269        int[] result = EMPTY_INT_ARRAY;
19270        for (int userId : userIds) {
19271            if (getBlockUninstallForUser(packageName, userId)) {
19272                result = ArrayUtils.appendInt(result, userId);
19273            }
19274        }
19275        return result;
19276    }
19277
19278    @Override
19279    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19280        final int callingUid = Binder.getCallingUid();
19281        if (getInstantAppPackageName(callingUid) != null
19282                && !isCallerSameApp(packageName, callingUid)) {
19283            return false;
19284        }
19285        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19286    }
19287
19288    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19289        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19290                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19291        try {
19292            if (dpm != null) {
19293                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19294                        /* callingUserOnly =*/ false);
19295                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19296                        : deviceOwnerComponentName.getPackageName();
19297                // Does the package contains the device owner?
19298                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19299                // this check is probably not needed, since DO should be registered as a device
19300                // admin on some user too. (Original bug for this: b/17657954)
19301                if (packageName.equals(deviceOwnerPackageName)) {
19302                    return true;
19303                }
19304                // Does it contain a device admin for any user?
19305                int[] users;
19306                if (userId == UserHandle.USER_ALL) {
19307                    users = sUserManager.getUserIds();
19308                } else {
19309                    users = new int[]{userId};
19310                }
19311                for (int i = 0; i < users.length; ++i) {
19312                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19313                        return true;
19314                    }
19315                }
19316            }
19317        } catch (RemoteException e) {
19318        }
19319        return false;
19320    }
19321
19322    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19323        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19324    }
19325
19326    /**
19327     *  This method is an internal method that could be get invoked either
19328     *  to delete an installed package or to clean up a failed installation.
19329     *  After deleting an installed package, a broadcast is sent to notify any
19330     *  listeners that the package has been removed. For cleaning up a failed
19331     *  installation, the broadcast is not necessary since the package's
19332     *  installation wouldn't have sent the initial broadcast either
19333     *  The key steps in deleting a package are
19334     *  deleting the package information in internal structures like mPackages,
19335     *  deleting the packages base directories through installd
19336     *  updating mSettings to reflect current status
19337     *  persisting settings for later use
19338     *  sending a broadcast if necessary
19339     */
19340    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19341        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19342        final boolean res;
19343
19344        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19345                ? UserHandle.USER_ALL : userId;
19346
19347        if (isPackageDeviceAdmin(packageName, removeUser)) {
19348            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19349            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19350        }
19351
19352        PackageSetting uninstalledPs = null;
19353        PackageParser.Package pkg = null;
19354
19355        // for the uninstall-updates case and restricted profiles, remember the per-
19356        // user handle installed state
19357        int[] allUsers;
19358        synchronized (mPackages) {
19359            uninstalledPs = mSettings.mPackages.get(packageName);
19360            if (uninstalledPs == null) {
19361                Slog.w(TAG, "Not removing non-existent package " + packageName);
19362                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19363            }
19364
19365            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19366                    && uninstalledPs.versionCode != versionCode) {
19367                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19368                        + uninstalledPs.versionCode + " != " + versionCode);
19369                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19370            }
19371
19372            // Static shared libs can be declared by any package, so let us not
19373            // allow removing a package if it provides a lib others depend on.
19374            pkg = mPackages.get(packageName);
19375
19376            allUsers = sUserManager.getUserIds();
19377
19378            if (pkg != null && pkg.staticSharedLibName != null) {
19379                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19380                        pkg.staticSharedLibVersion);
19381                if (libEntry != null) {
19382                    for (int currUserId : allUsers) {
19383                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19384                            continue;
19385                        }
19386                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19387                                libEntry.info, 0, currUserId);
19388                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19389                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19390                                    + " hosting lib " + libEntry.info.getName() + " version "
19391                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19392                                    + " for user " + currUserId);
19393                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19394                        }
19395                    }
19396                }
19397            }
19398
19399            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19400        }
19401
19402        final int freezeUser;
19403        if (isUpdatedSystemApp(uninstalledPs)
19404                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19405            // We're downgrading a system app, which will apply to all users, so
19406            // freeze them all during the downgrade
19407            freezeUser = UserHandle.USER_ALL;
19408        } else {
19409            freezeUser = removeUser;
19410        }
19411
19412        synchronized (mInstallLock) {
19413            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19414            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19415                    deleteFlags, "deletePackageX")) {
19416                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19417                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19418            }
19419            synchronized (mPackages) {
19420                if (res) {
19421                    if (pkg != null) {
19422                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19423                    }
19424                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19425                    updateInstantAppInstallerLocked(packageName);
19426                }
19427            }
19428        }
19429
19430        if (res) {
19431            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19432            info.sendPackageRemovedBroadcasts(killApp);
19433            info.sendSystemPackageUpdatedBroadcasts();
19434            info.sendSystemPackageAppearedBroadcasts();
19435        }
19436        // Force a gc here.
19437        Runtime.getRuntime().gc();
19438        // Delete the resources here after sending the broadcast to let
19439        // other processes clean up before deleting resources.
19440        if (info.args != null) {
19441            synchronized (mInstallLock) {
19442                info.args.doPostDeleteLI(true);
19443            }
19444        }
19445
19446        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19447    }
19448
19449    static class PackageRemovedInfo {
19450        final PackageSender packageSender;
19451        String removedPackage;
19452        String installerPackageName;
19453        int uid = -1;
19454        int removedAppId = -1;
19455        int[] origUsers;
19456        int[] removedUsers = null;
19457        int[] broadcastUsers = null;
19458        SparseArray<Integer> installReasons;
19459        boolean isRemovedPackageSystemUpdate = false;
19460        boolean isUpdate;
19461        boolean dataRemoved;
19462        boolean removedForAllUsers;
19463        boolean isStaticSharedLib;
19464        // Clean up resources deleted packages.
19465        InstallArgs args = null;
19466        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19467        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19468
19469        PackageRemovedInfo(PackageSender packageSender) {
19470            this.packageSender = packageSender;
19471        }
19472
19473        void sendPackageRemovedBroadcasts(boolean killApp) {
19474            sendPackageRemovedBroadcastInternal(killApp);
19475            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19476            for (int i = 0; i < childCount; i++) {
19477                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19478                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19479            }
19480        }
19481
19482        void sendSystemPackageUpdatedBroadcasts() {
19483            if (isRemovedPackageSystemUpdate) {
19484                sendSystemPackageUpdatedBroadcastsInternal();
19485                final int childCount = (removedChildPackages != null)
19486                        ? removedChildPackages.size() : 0;
19487                for (int i = 0; i < childCount; i++) {
19488                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19489                    if (childInfo.isRemovedPackageSystemUpdate) {
19490                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19491                    }
19492                }
19493            }
19494        }
19495
19496        void sendSystemPackageAppearedBroadcasts() {
19497            final int packageCount = (appearedChildPackages != null)
19498                    ? appearedChildPackages.size() : 0;
19499            for (int i = 0; i < packageCount; i++) {
19500                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19501                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19502                    true /*sendBootCompleted*/, false /*startReceiver*/,
19503                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19504            }
19505        }
19506
19507        private void sendSystemPackageUpdatedBroadcastsInternal() {
19508            Bundle extras = new Bundle(2);
19509            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19510            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19511            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19512                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19513            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19514                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19515            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19516                null, null, 0, removedPackage, null, null);
19517            if (installerPackageName != null) {
19518                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19519                        removedPackage, extras, 0 /*flags*/,
19520                        installerPackageName, null, null);
19521                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19522                        removedPackage, extras, 0 /*flags*/,
19523                        installerPackageName, null, null);
19524            }
19525        }
19526
19527        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19528            // Don't send static shared library removal broadcasts as these
19529            // libs are visible only the the apps that depend on them an one
19530            // cannot remove the library if it has a dependency.
19531            if (isStaticSharedLib) {
19532                return;
19533            }
19534            Bundle extras = new Bundle(2);
19535            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19536            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19537            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19538            if (isUpdate || isRemovedPackageSystemUpdate) {
19539                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19540            }
19541            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19542            if (removedPackage != null) {
19543                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19544                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19545                if (installerPackageName != null) {
19546                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19547                            removedPackage, extras, 0 /*flags*/,
19548                            installerPackageName, null, broadcastUsers);
19549                }
19550                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19551                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19552                        removedPackage, extras,
19553                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19554                        null, null, broadcastUsers);
19555                }
19556            }
19557            if (removedAppId >= 0) {
19558                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19559                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19560                    null, null, broadcastUsers);
19561            }
19562        }
19563
19564        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19565            removedUsers = userIds;
19566            if (removedUsers == null) {
19567                broadcastUsers = null;
19568                return;
19569            }
19570
19571            broadcastUsers = EMPTY_INT_ARRAY;
19572            for (int i = userIds.length - 1; i >= 0; --i) {
19573                final int userId = userIds[i];
19574                if (deletedPackageSetting.getInstantApp(userId)) {
19575                    continue;
19576                }
19577                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19578            }
19579        }
19580    }
19581
19582    /*
19583     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19584     * flag is not set, the data directory is removed as well.
19585     * make sure this flag is set for partially installed apps. If not its meaningless to
19586     * delete a partially installed application.
19587     */
19588    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19589            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19590        String packageName = ps.name;
19591        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19592        // Retrieve object to delete permissions for shared user later on
19593        final PackageParser.Package deletedPkg;
19594        final PackageSetting deletedPs;
19595        // reader
19596        synchronized (mPackages) {
19597            deletedPkg = mPackages.get(packageName);
19598            deletedPs = mSettings.mPackages.get(packageName);
19599            if (outInfo != null) {
19600                outInfo.removedPackage = packageName;
19601                outInfo.installerPackageName = ps.installerPackageName;
19602                outInfo.isStaticSharedLib = deletedPkg != null
19603                        && deletedPkg.staticSharedLibName != null;
19604                outInfo.populateUsers(deletedPs == null ? null
19605                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19606            }
19607        }
19608
19609        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19610
19611        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19612            final PackageParser.Package resolvedPkg;
19613            if (deletedPkg != null) {
19614                resolvedPkg = deletedPkg;
19615            } else {
19616                // We don't have a parsed package when it lives on an ejected
19617                // adopted storage device, so fake something together
19618                resolvedPkg = new PackageParser.Package(ps.name);
19619                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19620            }
19621            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19622                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19623            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19624            if (outInfo != null) {
19625                outInfo.dataRemoved = true;
19626            }
19627            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19628        }
19629
19630        int removedAppId = -1;
19631
19632        // writer
19633        synchronized (mPackages) {
19634            boolean installedStateChanged = false;
19635            if (deletedPs != null) {
19636                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19637                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19638                    clearDefaultBrowserIfNeeded(packageName);
19639                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19640                    removedAppId = mSettings.removePackageLPw(packageName);
19641                    if (outInfo != null) {
19642                        outInfo.removedAppId = removedAppId;
19643                    }
19644                    updatePermissionsLPw(deletedPs.name, null, 0);
19645                    if (deletedPs.sharedUser != null) {
19646                        // Remove permissions associated with package. Since runtime
19647                        // permissions are per user we have to kill the removed package
19648                        // or packages running under the shared user of the removed
19649                        // package if revoking the permissions requested only by the removed
19650                        // package is successful and this causes a change in gids.
19651                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19652                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19653                                    userId);
19654                            if (userIdToKill == UserHandle.USER_ALL
19655                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19656                                // If gids changed for this user, kill all affected packages.
19657                                mHandler.post(new Runnable() {
19658                                    @Override
19659                                    public void run() {
19660                                        // This has to happen with no lock held.
19661                                        killApplication(deletedPs.name, deletedPs.appId,
19662                                                KILL_APP_REASON_GIDS_CHANGED);
19663                                    }
19664                                });
19665                                break;
19666                            }
19667                        }
19668                    }
19669                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19670                }
19671                // make sure to preserve per-user disabled state if this removal was just
19672                // a downgrade of a system app to the factory package
19673                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19674                    if (DEBUG_REMOVE) {
19675                        Slog.d(TAG, "Propagating install state across downgrade");
19676                    }
19677                    for (int userId : allUserHandles) {
19678                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19679                        if (DEBUG_REMOVE) {
19680                            Slog.d(TAG, "    user " + userId + " => " + installed);
19681                        }
19682                        if (installed != ps.getInstalled(userId)) {
19683                            installedStateChanged = true;
19684                        }
19685                        ps.setInstalled(installed, userId);
19686                    }
19687                }
19688            }
19689            // can downgrade to reader
19690            if (writeSettings) {
19691                // Save settings now
19692                mSettings.writeLPr();
19693            }
19694            if (installedStateChanged) {
19695                mSettings.writeKernelMappingLPr(ps);
19696            }
19697        }
19698        if (removedAppId != -1) {
19699            // A user ID was deleted here. Go through all users and remove it
19700            // from KeyStore.
19701            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19702        }
19703    }
19704
19705    static boolean locationIsPrivileged(File path) {
19706        try {
19707            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19708                    .getCanonicalPath();
19709            return path.getCanonicalPath().startsWith(privilegedAppDir);
19710        } catch (IOException e) {
19711            Slog.e(TAG, "Unable to access code path " + path);
19712        }
19713        return false;
19714    }
19715
19716    /*
19717     * Tries to delete system package.
19718     */
19719    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19720            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19721            boolean writeSettings) {
19722        if (deletedPs.parentPackageName != null) {
19723            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19724            return false;
19725        }
19726
19727        final boolean applyUserRestrictions
19728                = (allUserHandles != null) && (outInfo.origUsers != null);
19729        final PackageSetting disabledPs;
19730        // Confirm if the system package has been updated
19731        // An updated system app can be deleted. This will also have to restore
19732        // the system pkg from system partition
19733        // reader
19734        synchronized (mPackages) {
19735            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19736        }
19737
19738        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19739                + " disabledPs=" + disabledPs);
19740
19741        if (disabledPs == null) {
19742            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19743            return false;
19744        } else if (DEBUG_REMOVE) {
19745            Slog.d(TAG, "Deleting system pkg from data partition");
19746        }
19747
19748        if (DEBUG_REMOVE) {
19749            if (applyUserRestrictions) {
19750                Slog.d(TAG, "Remembering install states:");
19751                for (int userId : allUserHandles) {
19752                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19753                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19754                }
19755            }
19756        }
19757
19758        // Delete the updated package
19759        outInfo.isRemovedPackageSystemUpdate = true;
19760        if (outInfo.removedChildPackages != null) {
19761            final int childCount = (deletedPs.childPackageNames != null)
19762                    ? deletedPs.childPackageNames.size() : 0;
19763            for (int i = 0; i < childCount; i++) {
19764                String childPackageName = deletedPs.childPackageNames.get(i);
19765                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19766                        .contains(childPackageName)) {
19767                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19768                            childPackageName);
19769                    if (childInfo != null) {
19770                        childInfo.isRemovedPackageSystemUpdate = true;
19771                    }
19772                }
19773            }
19774        }
19775
19776        if (disabledPs.versionCode < deletedPs.versionCode) {
19777            // Delete data for downgrades
19778            flags &= ~PackageManager.DELETE_KEEP_DATA;
19779        } else {
19780            // Preserve data by setting flag
19781            flags |= PackageManager.DELETE_KEEP_DATA;
19782        }
19783
19784        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19785                outInfo, writeSettings, disabledPs.pkg);
19786        if (!ret) {
19787            return false;
19788        }
19789
19790        // writer
19791        synchronized (mPackages) {
19792            // NOTE: The system package always needs to be enabled; even if it's for
19793            // a compressed stub. If we don't, installing the system package fails
19794            // during scan [scanning checks the disabled packages]. We will reverse
19795            // this later, after we've "installed" the stub.
19796            // Reinstate the old system package
19797            enableSystemPackageLPw(disabledPs.pkg);
19798            // Remove any native libraries from the upgraded package.
19799            removeNativeBinariesLI(deletedPs);
19800        }
19801
19802        // Install the system package
19803        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19804        try {
19805            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19806                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19807        } catch (PackageManagerException e) {
19808            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19809                    + e.getMessage());
19810            return false;
19811        } finally {
19812            if (disabledPs.pkg.isStub) {
19813                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19814            }
19815        }
19816        return true;
19817    }
19818
19819    /**
19820     * Installs a package that's already on the system partition.
19821     */
19822    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19823            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19824            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19825                    throws PackageManagerException {
19826        int parseFlags = mDefParseFlags
19827                | PackageParser.PARSE_MUST_BE_APK
19828                | PackageParser.PARSE_IS_SYSTEM
19829                | PackageParser.PARSE_IS_SYSTEM_DIR;
19830        if (isPrivileged || locationIsPrivileged(codePath)) {
19831            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19832        }
19833
19834        final PackageParser.Package newPkg =
19835                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19836
19837        try {
19838            // update shared libraries for the newly re-installed system package
19839            updateSharedLibrariesLPr(newPkg, null);
19840        } catch (PackageManagerException e) {
19841            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19842        }
19843
19844        prepareAppDataAfterInstallLIF(newPkg);
19845
19846        // writer
19847        synchronized (mPackages) {
19848            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19849
19850            // Propagate the permissions state as we do not want to drop on the floor
19851            // runtime permissions. The update permissions method below will take
19852            // care of removing obsolete permissions and grant install permissions.
19853            if (origPermissionState != null) {
19854                ps.getPermissionsState().copyFrom(origPermissionState);
19855            }
19856            updatePermissionsLPw(newPkg.packageName, newPkg,
19857                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19858
19859            final boolean applyUserRestrictions
19860                    = (allUserHandles != null) && (origUserHandles != null);
19861            if (applyUserRestrictions) {
19862                boolean installedStateChanged = false;
19863                if (DEBUG_REMOVE) {
19864                    Slog.d(TAG, "Propagating install state across reinstall");
19865                }
19866                for (int userId : allUserHandles) {
19867                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19868                    if (DEBUG_REMOVE) {
19869                        Slog.d(TAG, "    user " + userId + " => " + installed);
19870                    }
19871                    if (installed != ps.getInstalled(userId)) {
19872                        installedStateChanged = true;
19873                    }
19874                    ps.setInstalled(installed, userId);
19875
19876                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19877                }
19878                // Regardless of writeSettings we need to ensure that this restriction
19879                // state propagation is persisted
19880                mSettings.writeAllUsersPackageRestrictionsLPr();
19881                if (installedStateChanged) {
19882                    mSettings.writeKernelMappingLPr(ps);
19883                }
19884            }
19885            // can downgrade to reader here
19886            if (writeSettings) {
19887                mSettings.writeLPr();
19888            }
19889        }
19890        return newPkg;
19891    }
19892
19893    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19894            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19895            PackageRemovedInfo outInfo, boolean writeSettings,
19896            PackageParser.Package replacingPackage) {
19897        synchronized (mPackages) {
19898            if (outInfo != null) {
19899                outInfo.uid = ps.appId;
19900            }
19901
19902            if (outInfo != null && outInfo.removedChildPackages != null) {
19903                final int childCount = (ps.childPackageNames != null)
19904                        ? ps.childPackageNames.size() : 0;
19905                for (int i = 0; i < childCount; i++) {
19906                    String childPackageName = ps.childPackageNames.get(i);
19907                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19908                    if (childPs == null) {
19909                        return false;
19910                    }
19911                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19912                            childPackageName);
19913                    if (childInfo != null) {
19914                        childInfo.uid = childPs.appId;
19915                    }
19916                }
19917            }
19918        }
19919
19920        // Delete package data from internal structures and also remove data if flag is set
19921        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19922
19923        // Delete the child packages data
19924        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19925        for (int i = 0; i < childCount; i++) {
19926            PackageSetting childPs;
19927            synchronized (mPackages) {
19928                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19929            }
19930            if (childPs != null) {
19931                PackageRemovedInfo childOutInfo = (outInfo != null
19932                        && outInfo.removedChildPackages != null)
19933                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19934                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19935                        && (replacingPackage != null
19936                        && !replacingPackage.hasChildPackage(childPs.name))
19937                        ? flags & ~DELETE_KEEP_DATA : flags;
19938                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19939                        deleteFlags, writeSettings);
19940            }
19941        }
19942
19943        // Delete application code and resources only for parent packages
19944        if (ps.parentPackageName == null) {
19945            if (deleteCodeAndResources && (outInfo != null)) {
19946                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19947                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19948                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19949            }
19950        }
19951
19952        return true;
19953    }
19954
19955    @Override
19956    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19957            int userId) {
19958        mContext.enforceCallingOrSelfPermission(
19959                android.Manifest.permission.DELETE_PACKAGES, null);
19960        synchronized (mPackages) {
19961            // Cannot block uninstall of static shared libs as they are
19962            // considered a part of the using app (emulating static linking).
19963            // Also static libs are installed always on internal storage.
19964            PackageParser.Package pkg = mPackages.get(packageName);
19965            if (pkg != null && pkg.staticSharedLibName != null) {
19966                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19967                        + " providing static shared library: " + pkg.staticSharedLibName);
19968                return false;
19969            }
19970            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19971            mSettings.writePackageRestrictionsLPr(userId);
19972        }
19973        return true;
19974    }
19975
19976    @Override
19977    public boolean getBlockUninstallForUser(String packageName, int userId) {
19978        synchronized (mPackages) {
19979            final PackageSetting ps = mSettings.mPackages.get(packageName);
19980            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19981                return false;
19982            }
19983            return mSettings.getBlockUninstallLPr(userId, packageName);
19984        }
19985    }
19986
19987    @Override
19988    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19989        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19990        synchronized (mPackages) {
19991            PackageSetting ps = mSettings.mPackages.get(packageName);
19992            if (ps == null) {
19993                Log.w(TAG, "Package doesn't exist: " + packageName);
19994                return false;
19995            }
19996            if (systemUserApp) {
19997                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19998            } else {
19999                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20000            }
20001            mSettings.writeLPr();
20002        }
20003        return true;
20004    }
20005
20006    /*
20007     * This method handles package deletion in general
20008     */
20009    private boolean deletePackageLIF(String packageName, UserHandle user,
20010            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
20011            PackageRemovedInfo outInfo, boolean writeSettings,
20012            PackageParser.Package replacingPackage) {
20013        if (packageName == null) {
20014            Slog.w(TAG, "Attempt to delete null packageName.");
20015            return false;
20016        }
20017
20018        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
20019
20020        PackageSetting ps;
20021        synchronized (mPackages) {
20022            ps = mSettings.mPackages.get(packageName);
20023            if (ps == null) {
20024                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20025                return false;
20026            }
20027
20028            if (ps.parentPackageName != null && (!isSystemApp(ps)
20029                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
20030                if (DEBUG_REMOVE) {
20031                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
20032                            + ((user == null) ? UserHandle.USER_ALL : user));
20033                }
20034                final int removedUserId = (user != null) ? user.getIdentifier()
20035                        : UserHandle.USER_ALL;
20036                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
20037                    return false;
20038                }
20039                markPackageUninstalledForUserLPw(ps, user);
20040                scheduleWritePackageRestrictionsLocked(user);
20041                return true;
20042            }
20043        }
20044
20045        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
20046                && user.getIdentifier() != UserHandle.USER_ALL)) {
20047            // The caller is asking that the package only be deleted for a single
20048            // user.  To do this, we just mark its uninstalled state and delete
20049            // its data. If this is a system app, we only allow this to happen if
20050            // they have set the special DELETE_SYSTEM_APP which requests different
20051            // semantics than normal for uninstalling system apps.
20052            markPackageUninstalledForUserLPw(ps, user);
20053
20054            if (!isSystemApp(ps)) {
20055                // Do not uninstall the APK if an app should be cached
20056                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
20057                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
20058                    // Other user still have this package installed, so all
20059                    // we need to do is clear this user's data and save that
20060                    // it is uninstalled.
20061                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
20062                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20063                        return false;
20064                    }
20065                    scheduleWritePackageRestrictionsLocked(user);
20066                    return true;
20067                } else {
20068                    // We need to set it back to 'installed' so the uninstall
20069                    // broadcasts will be sent correctly.
20070                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20071                    ps.setInstalled(true, user.getIdentifier());
20072                    mSettings.writeKernelMappingLPr(ps);
20073                }
20074            } else {
20075                // This is a system app, so we assume that the
20076                // other users still have this package installed, so all
20077                // we need to do is clear this user's data and save that
20078                // it is uninstalled.
20079                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20080                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20081                    return false;
20082                }
20083                scheduleWritePackageRestrictionsLocked(user);
20084                return true;
20085            }
20086        }
20087
20088        // If we are deleting a composite package for all users, keep track
20089        // of result for each child.
20090        if (ps.childPackageNames != null && outInfo != null) {
20091            synchronized (mPackages) {
20092                final int childCount = ps.childPackageNames.size();
20093                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20094                for (int i = 0; i < childCount; i++) {
20095                    String childPackageName = ps.childPackageNames.get(i);
20096                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20097                    childInfo.removedPackage = childPackageName;
20098                    childInfo.installerPackageName = ps.installerPackageName;
20099                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20100                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20101                    if (childPs != null) {
20102                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20103                    }
20104                }
20105            }
20106        }
20107
20108        boolean ret = false;
20109        if (isSystemApp(ps)) {
20110            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20111            // When an updated system application is deleted we delete the existing resources
20112            // as well and fall back to existing code in system partition
20113            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20114        } else {
20115            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20116            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20117                    outInfo, writeSettings, replacingPackage);
20118        }
20119
20120        // Take a note whether we deleted the package for all users
20121        if (outInfo != null) {
20122            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20123            if (outInfo.removedChildPackages != null) {
20124                synchronized (mPackages) {
20125                    final int childCount = outInfo.removedChildPackages.size();
20126                    for (int i = 0; i < childCount; i++) {
20127                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20128                        if (childInfo != null) {
20129                            childInfo.removedForAllUsers = mPackages.get(
20130                                    childInfo.removedPackage) == null;
20131                        }
20132                    }
20133                }
20134            }
20135            // If we uninstalled an update to a system app there may be some
20136            // child packages that appeared as they are declared in the system
20137            // app but were not declared in the update.
20138            if (isSystemApp(ps)) {
20139                synchronized (mPackages) {
20140                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20141                    final int childCount = (updatedPs.childPackageNames != null)
20142                            ? updatedPs.childPackageNames.size() : 0;
20143                    for (int i = 0; i < childCount; i++) {
20144                        String childPackageName = updatedPs.childPackageNames.get(i);
20145                        if (outInfo.removedChildPackages == null
20146                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20147                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20148                            if (childPs == null) {
20149                                continue;
20150                            }
20151                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20152                            installRes.name = childPackageName;
20153                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20154                            installRes.pkg = mPackages.get(childPackageName);
20155                            installRes.uid = childPs.pkg.applicationInfo.uid;
20156                            if (outInfo.appearedChildPackages == null) {
20157                                outInfo.appearedChildPackages = new ArrayMap<>();
20158                            }
20159                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20160                        }
20161                    }
20162                }
20163            }
20164        }
20165
20166        return ret;
20167    }
20168
20169    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20170        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20171                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20172        for (int nextUserId : userIds) {
20173            if (DEBUG_REMOVE) {
20174                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20175            }
20176            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20177                    false /*installed*/,
20178                    true /*stopped*/,
20179                    true /*notLaunched*/,
20180                    false /*hidden*/,
20181                    false /*suspended*/,
20182                    false /*instantApp*/,
20183                    false /*virtualPreload*/,
20184                    null /*lastDisableAppCaller*/,
20185                    null /*enabledComponents*/,
20186                    null /*disabledComponents*/,
20187                    ps.readUserState(nextUserId).domainVerificationStatus,
20188                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20189        }
20190        mSettings.writeKernelMappingLPr(ps);
20191    }
20192
20193    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20194            PackageRemovedInfo outInfo) {
20195        final PackageParser.Package pkg;
20196        synchronized (mPackages) {
20197            pkg = mPackages.get(ps.name);
20198        }
20199
20200        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20201                : new int[] {userId};
20202        for (int nextUserId : userIds) {
20203            if (DEBUG_REMOVE) {
20204                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20205                        + nextUserId);
20206            }
20207
20208            destroyAppDataLIF(pkg, userId,
20209                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20210            destroyAppProfilesLIF(pkg, userId);
20211            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20212            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20213            schedulePackageCleaning(ps.name, nextUserId, false);
20214            synchronized (mPackages) {
20215                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20216                    scheduleWritePackageRestrictionsLocked(nextUserId);
20217                }
20218                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20219            }
20220        }
20221
20222        if (outInfo != null) {
20223            outInfo.removedPackage = ps.name;
20224            outInfo.installerPackageName = ps.installerPackageName;
20225            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20226            outInfo.removedAppId = ps.appId;
20227            outInfo.removedUsers = userIds;
20228            outInfo.broadcastUsers = userIds;
20229        }
20230
20231        return true;
20232    }
20233
20234    private final class ClearStorageConnection implements ServiceConnection {
20235        IMediaContainerService mContainerService;
20236
20237        @Override
20238        public void onServiceConnected(ComponentName name, IBinder service) {
20239            synchronized (this) {
20240                mContainerService = IMediaContainerService.Stub
20241                        .asInterface(Binder.allowBlocking(service));
20242                notifyAll();
20243            }
20244        }
20245
20246        @Override
20247        public void onServiceDisconnected(ComponentName name) {
20248        }
20249    }
20250
20251    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20252        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20253
20254        final boolean mounted;
20255        if (Environment.isExternalStorageEmulated()) {
20256            mounted = true;
20257        } else {
20258            final String status = Environment.getExternalStorageState();
20259
20260            mounted = status.equals(Environment.MEDIA_MOUNTED)
20261                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20262        }
20263
20264        if (!mounted) {
20265            return;
20266        }
20267
20268        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20269        int[] users;
20270        if (userId == UserHandle.USER_ALL) {
20271            users = sUserManager.getUserIds();
20272        } else {
20273            users = new int[] { userId };
20274        }
20275        final ClearStorageConnection conn = new ClearStorageConnection();
20276        if (mContext.bindServiceAsUser(
20277                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20278            try {
20279                for (int curUser : users) {
20280                    long timeout = SystemClock.uptimeMillis() + 5000;
20281                    synchronized (conn) {
20282                        long now;
20283                        while (conn.mContainerService == null &&
20284                                (now = SystemClock.uptimeMillis()) < timeout) {
20285                            try {
20286                                conn.wait(timeout - now);
20287                            } catch (InterruptedException e) {
20288                            }
20289                        }
20290                    }
20291                    if (conn.mContainerService == null) {
20292                        return;
20293                    }
20294
20295                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20296                    clearDirectory(conn.mContainerService,
20297                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20298                    if (allData) {
20299                        clearDirectory(conn.mContainerService,
20300                                userEnv.buildExternalStorageAppDataDirs(packageName));
20301                        clearDirectory(conn.mContainerService,
20302                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20303                    }
20304                }
20305            } finally {
20306                mContext.unbindService(conn);
20307            }
20308        }
20309    }
20310
20311    @Override
20312    public void clearApplicationProfileData(String packageName) {
20313        enforceSystemOrRoot("Only the system can clear all profile data");
20314
20315        final PackageParser.Package pkg;
20316        synchronized (mPackages) {
20317            pkg = mPackages.get(packageName);
20318        }
20319
20320        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20321            synchronized (mInstallLock) {
20322                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20323            }
20324        }
20325    }
20326
20327    @Override
20328    public void clearApplicationUserData(final String packageName,
20329            final IPackageDataObserver observer, final int userId) {
20330        mContext.enforceCallingOrSelfPermission(
20331                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20332
20333        final int callingUid = Binder.getCallingUid();
20334        enforceCrossUserPermission(callingUid, userId,
20335                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20336
20337        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20338        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20339        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20340            throw new SecurityException("Cannot clear data for a protected package: "
20341                    + packageName);
20342        }
20343        // Queue up an async operation since the package deletion may take a little while.
20344        mHandler.post(new Runnable() {
20345            public void run() {
20346                mHandler.removeCallbacks(this);
20347                final boolean succeeded;
20348                if (!filterApp) {
20349                    try (PackageFreezer freezer = freezePackage(packageName,
20350                            "clearApplicationUserData")) {
20351                        synchronized (mInstallLock) {
20352                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20353                        }
20354                        clearExternalStorageDataSync(packageName, userId, true);
20355                        synchronized (mPackages) {
20356                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20357                                    packageName, userId);
20358                        }
20359                    }
20360                    if (succeeded) {
20361                        // invoke DeviceStorageMonitor's update method to clear any notifications
20362                        DeviceStorageMonitorInternal dsm = LocalServices
20363                                .getService(DeviceStorageMonitorInternal.class);
20364                        if (dsm != null) {
20365                            dsm.checkMemory();
20366                        }
20367                    }
20368                } else {
20369                    succeeded = false;
20370                }
20371                if (observer != null) {
20372                    try {
20373                        observer.onRemoveCompleted(packageName, succeeded);
20374                    } catch (RemoteException e) {
20375                        Log.i(TAG, "Observer no longer exists.");
20376                    }
20377                } //end if observer
20378            } //end run
20379        });
20380    }
20381
20382    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20383        if (packageName == null) {
20384            Slog.w(TAG, "Attempt to delete null packageName.");
20385            return false;
20386        }
20387
20388        // Try finding details about the requested package
20389        PackageParser.Package pkg;
20390        synchronized (mPackages) {
20391            pkg = mPackages.get(packageName);
20392            if (pkg == null) {
20393                final PackageSetting ps = mSettings.mPackages.get(packageName);
20394                if (ps != null) {
20395                    pkg = ps.pkg;
20396                }
20397            }
20398
20399            if (pkg == null) {
20400                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20401                return false;
20402            }
20403
20404            PackageSetting ps = (PackageSetting) pkg.mExtras;
20405            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20406        }
20407
20408        clearAppDataLIF(pkg, userId,
20409                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20410
20411        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20412        removeKeystoreDataIfNeeded(userId, appId);
20413
20414        UserManagerInternal umInternal = getUserManagerInternal();
20415        final int flags;
20416        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20417            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20418        } else if (umInternal.isUserRunning(userId)) {
20419            flags = StorageManager.FLAG_STORAGE_DE;
20420        } else {
20421            flags = 0;
20422        }
20423        prepareAppDataContentsLIF(pkg, userId, flags);
20424
20425        return true;
20426    }
20427
20428    /**
20429     * Reverts user permission state changes (permissions and flags) in
20430     * all packages for a given user.
20431     *
20432     * @param userId The device user for which to do a reset.
20433     */
20434    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20435        final int packageCount = mPackages.size();
20436        for (int i = 0; i < packageCount; i++) {
20437            PackageParser.Package pkg = mPackages.valueAt(i);
20438            PackageSetting ps = (PackageSetting) pkg.mExtras;
20439            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20440        }
20441    }
20442
20443    private void resetNetworkPolicies(int userId) {
20444        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20445    }
20446
20447    /**
20448     * Reverts user permission state changes (permissions and flags).
20449     *
20450     * @param ps The package for which to reset.
20451     * @param userId The device user for which to do a reset.
20452     */
20453    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20454            final PackageSetting ps, final int userId) {
20455        if (ps.pkg == null) {
20456            return;
20457        }
20458
20459        // These are flags that can change base on user actions.
20460        final int userSettableMask = FLAG_PERMISSION_USER_SET
20461                | FLAG_PERMISSION_USER_FIXED
20462                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20463                | FLAG_PERMISSION_REVIEW_REQUIRED;
20464
20465        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20466                | FLAG_PERMISSION_POLICY_FIXED;
20467
20468        boolean writeInstallPermissions = false;
20469        boolean writeRuntimePermissions = false;
20470
20471        final int permissionCount = ps.pkg.requestedPermissions.size();
20472        for (int i = 0; i < permissionCount; i++) {
20473            String permission = ps.pkg.requestedPermissions.get(i);
20474
20475            BasePermission bp = mSettings.mPermissions.get(permission);
20476            if (bp == null) {
20477                continue;
20478            }
20479
20480            // If shared user we just reset the state to which only this app contributed.
20481            if (ps.sharedUser != null) {
20482                boolean used = false;
20483                final int packageCount = ps.sharedUser.packages.size();
20484                for (int j = 0; j < packageCount; j++) {
20485                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20486                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20487                            && pkg.pkg.requestedPermissions.contains(permission)) {
20488                        used = true;
20489                        break;
20490                    }
20491                }
20492                if (used) {
20493                    continue;
20494                }
20495            }
20496
20497            PermissionsState permissionsState = ps.getPermissionsState();
20498
20499            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20500
20501            // Always clear the user settable flags.
20502            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20503                    bp.name) != null;
20504            // If permission review is enabled and this is a legacy app, mark the
20505            // permission as requiring a review as this is the initial state.
20506            int flags = 0;
20507            if (mPermissionReviewRequired
20508                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20509                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20510            }
20511            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20512                if (hasInstallState) {
20513                    writeInstallPermissions = true;
20514                } else {
20515                    writeRuntimePermissions = true;
20516                }
20517            }
20518
20519            // Below is only runtime permission handling.
20520            if (!bp.isRuntime()) {
20521                continue;
20522            }
20523
20524            // Never clobber system or policy.
20525            if ((oldFlags & policyOrSystemFlags) != 0) {
20526                continue;
20527            }
20528
20529            // If this permission was granted by default, make sure it is.
20530            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20531                if (permissionsState.grantRuntimePermission(bp, userId)
20532                        != PERMISSION_OPERATION_FAILURE) {
20533                    writeRuntimePermissions = true;
20534                }
20535            // If permission review is enabled the permissions for a legacy apps
20536            // are represented as constantly granted runtime ones, so don't revoke.
20537            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20538                // Otherwise, reset the permission.
20539                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20540                switch (revokeResult) {
20541                    case PERMISSION_OPERATION_SUCCESS:
20542                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20543                        writeRuntimePermissions = true;
20544                        final int appId = ps.appId;
20545                        mHandler.post(new Runnable() {
20546                            @Override
20547                            public void run() {
20548                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20549                            }
20550                        });
20551                    } break;
20552                }
20553            }
20554        }
20555
20556        // Synchronously write as we are taking permissions away.
20557        if (writeRuntimePermissions) {
20558            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20559        }
20560
20561        // Synchronously write as we are taking permissions away.
20562        if (writeInstallPermissions) {
20563            mSettings.writeLPr();
20564        }
20565    }
20566
20567    /**
20568     * Remove entries from the keystore daemon. Will only remove it if the
20569     * {@code appId} is valid.
20570     */
20571    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20572        if (appId < 0) {
20573            return;
20574        }
20575
20576        final KeyStore keyStore = KeyStore.getInstance();
20577        if (keyStore != null) {
20578            if (userId == UserHandle.USER_ALL) {
20579                for (final int individual : sUserManager.getUserIds()) {
20580                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20581                }
20582            } else {
20583                keyStore.clearUid(UserHandle.getUid(userId, appId));
20584            }
20585        } else {
20586            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20587        }
20588    }
20589
20590    @Override
20591    public void deleteApplicationCacheFiles(final String packageName,
20592            final IPackageDataObserver observer) {
20593        final int userId = UserHandle.getCallingUserId();
20594        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20595    }
20596
20597    @Override
20598    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20599            final IPackageDataObserver observer) {
20600        final int callingUid = Binder.getCallingUid();
20601        mContext.enforceCallingOrSelfPermission(
20602                android.Manifest.permission.DELETE_CACHE_FILES, null);
20603        enforceCrossUserPermission(callingUid, userId,
20604                /* requireFullPermission= */ true, /* checkShell= */ false,
20605                "delete application cache files");
20606        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20607                android.Manifest.permission.ACCESS_INSTANT_APPS);
20608
20609        final PackageParser.Package pkg;
20610        synchronized (mPackages) {
20611            pkg = mPackages.get(packageName);
20612        }
20613
20614        // Queue up an async operation since the package deletion may take a little while.
20615        mHandler.post(new Runnable() {
20616            public void run() {
20617                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20618                boolean doClearData = true;
20619                if (ps != null) {
20620                    final boolean targetIsInstantApp =
20621                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20622                    doClearData = !targetIsInstantApp
20623                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20624                }
20625                if (doClearData) {
20626                    synchronized (mInstallLock) {
20627                        final int flags = StorageManager.FLAG_STORAGE_DE
20628                                | StorageManager.FLAG_STORAGE_CE;
20629                        // We're only clearing cache files, so we don't care if the
20630                        // app is unfrozen and still able to run
20631                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20632                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20633                    }
20634                    clearExternalStorageDataSync(packageName, userId, false);
20635                }
20636                if (observer != null) {
20637                    try {
20638                        observer.onRemoveCompleted(packageName, true);
20639                    } catch (RemoteException e) {
20640                        Log.i(TAG, "Observer no longer exists.");
20641                    }
20642                }
20643            }
20644        });
20645    }
20646
20647    @Override
20648    public void getPackageSizeInfo(final String packageName, int userHandle,
20649            final IPackageStatsObserver observer) {
20650        throw new UnsupportedOperationException(
20651                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20652    }
20653
20654    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20655        final PackageSetting ps;
20656        synchronized (mPackages) {
20657            ps = mSettings.mPackages.get(packageName);
20658            if (ps == null) {
20659                Slog.w(TAG, "Failed to find settings for " + packageName);
20660                return false;
20661            }
20662        }
20663
20664        final String[] packageNames = { packageName };
20665        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20666        final String[] codePaths = { ps.codePathString };
20667
20668        try {
20669            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20670                    ps.appId, ceDataInodes, codePaths, stats);
20671
20672            // For now, ignore code size of packages on system partition
20673            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20674                stats.codeSize = 0;
20675            }
20676
20677            // External clients expect these to be tracked separately
20678            stats.dataSize -= stats.cacheSize;
20679
20680        } catch (InstallerException e) {
20681            Slog.w(TAG, String.valueOf(e));
20682            return false;
20683        }
20684
20685        return true;
20686    }
20687
20688    private int getUidTargetSdkVersionLockedLPr(int uid) {
20689        Object obj = mSettings.getUserIdLPr(uid);
20690        if (obj instanceof SharedUserSetting) {
20691            final SharedUserSetting sus = (SharedUserSetting) obj;
20692            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20693            final Iterator<PackageSetting> it = sus.packages.iterator();
20694            while (it.hasNext()) {
20695                final PackageSetting ps = it.next();
20696                if (ps.pkg != null) {
20697                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20698                    if (v < vers) vers = v;
20699                }
20700            }
20701            return vers;
20702        } else if (obj instanceof PackageSetting) {
20703            final PackageSetting ps = (PackageSetting) obj;
20704            if (ps.pkg != null) {
20705                return ps.pkg.applicationInfo.targetSdkVersion;
20706            }
20707        }
20708        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20709    }
20710
20711    @Override
20712    public void addPreferredActivity(IntentFilter filter, int match,
20713            ComponentName[] set, ComponentName activity, int userId) {
20714        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20715                "Adding preferred");
20716    }
20717
20718    private void addPreferredActivityInternal(IntentFilter filter, int match,
20719            ComponentName[] set, ComponentName activity, boolean always, int userId,
20720            String opname) {
20721        // writer
20722        int callingUid = Binder.getCallingUid();
20723        enforceCrossUserPermission(callingUid, userId,
20724                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20725        if (filter.countActions() == 0) {
20726            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20727            return;
20728        }
20729        synchronized (mPackages) {
20730            if (mContext.checkCallingOrSelfPermission(
20731                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20732                    != PackageManager.PERMISSION_GRANTED) {
20733                if (getUidTargetSdkVersionLockedLPr(callingUid)
20734                        < Build.VERSION_CODES.FROYO) {
20735                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20736                            + callingUid);
20737                    return;
20738                }
20739                mContext.enforceCallingOrSelfPermission(
20740                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20741            }
20742
20743            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20744            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20745                    + userId + ":");
20746            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20747            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20748            scheduleWritePackageRestrictionsLocked(userId);
20749            postPreferredActivityChangedBroadcast(userId);
20750        }
20751    }
20752
20753    private void postPreferredActivityChangedBroadcast(int userId) {
20754        mHandler.post(() -> {
20755            final IActivityManager am = ActivityManager.getService();
20756            if (am == null) {
20757                return;
20758            }
20759
20760            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20761            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20762            try {
20763                am.broadcastIntent(null, intent, null, null,
20764                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20765                        null, false, false, userId);
20766            } catch (RemoteException e) {
20767            }
20768        });
20769    }
20770
20771    @Override
20772    public void replacePreferredActivity(IntentFilter filter, int match,
20773            ComponentName[] set, ComponentName activity, int userId) {
20774        if (filter.countActions() != 1) {
20775            throw new IllegalArgumentException(
20776                    "replacePreferredActivity expects filter to have only 1 action.");
20777        }
20778        if (filter.countDataAuthorities() != 0
20779                || filter.countDataPaths() != 0
20780                || filter.countDataSchemes() > 1
20781                || filter.countDataTypes() != 0) {
20782            throw new IllegalArgumentException(
20783                    "replacePreferredActivity expects filter to have no data authorities, " +
20784                    "paths, or types; and at most one scheme.");
20785        }
20786
20787        final int callingUid = Binder.getCallingUid();
20788        enforceCrossUserPermission(callingUid, userId,
20789                true /* requireFullPermission */, false /* checkShell */,
20790                "replace preferred activity");
20791        synchronized (mPackages) {
20792            if (mContext.checkCallingOrSelfPermission(
20793                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20794                    != PackageManager.PERMISSION_GRANTED) {
20795                if (getUidTargetSdkVersionLockedLPr(callingUid)
20796                        < Build.VERSION_CODES.FROYO) {
20797                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20798                            + Binder.getCallingUid());
20799                    return;
20800                }
20801                mContext.enforceCallingOrSelfPermission(
20802                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20803            }
20804
20805            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20806            if (pir != null) {
20807                // Get all of the existing entries that exactly match this filter.
20808                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20809                if (existing != null && existing.size() == 1) {
20810                    PreferredActivity cur = existing.get(0);
20811                    if (DEBUG_PREFERRED) {
20812                        Slog.i(TAG, "Checking replace of preferred:");
20813                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20814                        if (!cur.mPref.mAlways) {
20815                            Slog.i(TAG, "  -- CUR; not mAlways!");
20816                        } else {
20817                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20818                            Slog.i(TAG, "  -- CUR: mSet="
20819                                    + Arrays.toString(cur.mPref.mSetComponents));
20820                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20821                            Slog.i(TAG, "  -- NEW: mMatch="
20822                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20823                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20824                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20825                        }
20826                    }
20827                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20828                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20829                            && cur.mPref.sameSet(set)) {
20830                        // Setting the preferred activity to what it happens to be already
20831                        if (DEBUG_PREFERRED) {
20832                            Slog.i(TAG, "Replacing with same preferred activity "
20833                                    + cur.mPref.mShortComponent + " for user "
20834                                    + userId + ":");
20835                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20836                        }
20837                        return;
20838                    }
20839                }
20840
20841                if (existing != null) {
20842                    if (DEBUG_PREFERRED) {
20843                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20844                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20845                    }
20846                    for (int i = 0; i < existing.size(); i++) {
20847                        PreferredActivity pa = existing.get(i);
20848                        if (DEBUG_PREFERRED) {
20849                            Slog.i(TAG, "Removing existing preferred activity "
20850                                    + pa.mPref.mComponent + ":");
20851                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20852                        }
20853                        pir.removeFilter(pa);
20854                    }
20855                }
20856            }
20857            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20858                    "Replacing preferred");
20859        }
20860    }
20861
20862    @Override
20863    public void clearPackagePreferredActivities(String packageName) {
20864        final int callingUid = Binder.getCallingUid();
20865        if (getInstantAppPackageName(callingUid) != null) {
20866            return;
20867        }
20868        // writer
20869        synchronized (mPackages) {
20870            PackageParser.Package pkg = mPackages.get(packageName);
20871            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20872                if (mContext.checkCallingOrSelfPermission(
20873                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20874                        != PackageManager.PERMISSION_GRANTED) {
20875                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20876                            < Build.VERSION_CODES.FROYO) {
20877                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20878                                + callingUid);
20879                        return;
20880                    }
20881                    mContext.enforceCallingOrSelfPermission(
20882                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20883                }
20884            }
20885            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20886            if (ps != null
20887                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20888                return;
20889            }
20890            int user = UserHandle.getCallingUserId();
20891            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20892                scheduleWritePackageRestrictionsLocked(user);
20893            }
20894        }
20895    }
20896
20897    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20898    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20899        ArrayList<PreferredActivity> removed = null;
20900        boolean changed = false;
20901        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20902            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20903            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20904            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20905                continue;
20906            }
20907            Iterator<PreferredActivity> it = pir.filterIterator();
20908            while (it.hasNext()) {
20909                PreferredActivity pa = it.next();
20910                // Mark entry for removal only if it matches the package name
20911                // and the entry is of type "always".
20912                if (packageName == null ||
20913                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20914                                && pa.mPref.mAlways)) {
20915                    if (removed == null) {
20916                        removed = new ArrayList<PreferredActivity>();
20917                    }
20918                    removed.add(pa);
20919                }
20920            }
20921            if (removed != null) {
20922                for (int j=0; j<removed.size(); j++) {
20923                    PreferredActivity pa = removed.get(j);
20924                    pir.removeFilter(pa);
20925                }
20926                changed = true;
20927            }
20928        }
20929        if (changed) {
20930            postPreferredActivityChangedBroadcast(userId);
20931        }
20932        return changed;
20933    }
20934
20935    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20936    private void clearIntentFilterVerificationsLPw(int userId) {
20937        final int packageCount = mPackages.size();
20938        for (int i = 0; i < packageCount; i++) {
20939            PackageParser.Package pkg = mPackages.valueAt(i);
20940            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20941        }
20942    }
20943
20944    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20945    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20946        if (userId == UserHandle.USER_ALL) {
20947            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20948                    sUserManager.getUserIds())) {
20949                for (int oneUserId : sUserManager.getUserIds()) {
20950                    scheduleWritePackageRestrictionsLocked(oneUserId);
20951                }
20952            }
20953        } else {
20954            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20955                scheduleWritePackageRestrictionsLocked(userId);
20956            }
20957        }
20958    }
20959
20960    /** Clears state for all users, and touches intent filter verification policy */
20961    void clearDefaultBrowserIfNeeded(String packageName) {
20962        for (int oneUserId : sUserManager.getUserIds()) {
20963            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20964        }
20965    }
20966
20967    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20968        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20969        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20970            if (packageName.equals(defaultBrowserPackageName)) {
20971                setDefaultBrowserPackageName(null, userId);
20972            }
20973        }
20974    }
20975
20976    @Override
20977    public void resetApplicationPreferences(int userId) {
20978        mContext.enforceCallingOrSelfPermission(
20979                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20980        final long identity = Binder.clearCallingIdentity();
20981        // writer
20982        try {
20983            synchronized (mPackages) {
20984                clearPackagePreferredActivitiesLPw(null, userId);
20985                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20986                // TODO: We have to reset the default SMS and Phone. This requires
20987                // significant refactoring to keep all default apps in the package
20988                // manager (cleaner but more work) or have the services provide
20989                // callbacks to the package manager to request a default app reset.
20990                applyFactoryDefaultBrowserLPw(userId);
20991                clearIntentFilterVerificationsLPw(userId);
20992                primeDomainVerificationsLPw(userId);
20993                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20994                scheduleWritePackageRestrictionsLocked(userId);
20995            }
20996            resetNetworkPolicies(userId);
20997        } finally {
20998            Binder.restoreCallingIdentity(identity);
20999        }
21000    }
21001
21002    @Override
21003    public int getPreferredActivities(List<IntentFilter> outFilters,
21004            List<ComponentName> outActivities, String packageName) {
21005        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21006            return 0;
21007        }
21008        int num = 0;
21009        final int userId = UserHandle.getCallingUserId();
21010        // reader
21011        synchronized (mPackages) {
21012            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
21013            if (pir != null) {
21014                final Iterator<PreferredActivity> it = pir.filterIterator();
21015                while (it.hasNext()) {
21016                    final PreferredActivity pa = it.next();
21017                    if (packageName == null
21018                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
21019                                    && pa.mPref.mAlways)) {
21020                        if (outFilters != null) {
21021                            outFilters.add(new IntentFilter(pa));
21022                        }
21023                        if (outActivities != null) {
21024                            outActivities.add(pa.mPref.mComponent);
21025                        }
21026                    }
21027                }
21028            }
21029        }
21030
21031        return num;
21032    }
21033
21034    @Override
21035    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
21036            int userId) {
21037        int callingUid = Binder.getCallingUid();
21038        if (callingUid != Process.SYSTEM_UID) {
21039            throw new SecurityException(
21040                    "addPersistentPreferredActivity can only be run by the system");
21041        }
21042        if (filter.countActions() == 0) {
21043            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
21044            return;
21045        }
21046        synchronized (mPackages) {
21047            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
21048                    ":");
21049            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
21050            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
21051                    new PersistentPreferredActivity(filter, activity));
21052            scheduleWritePackageRestrictionsLocked(userId);
21053            postPreferredActivityChangedBroadcast(userId);
21054        }
21055    }
21056
21057    @Override
21058    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
21059        int callingUid = Binder.getCallingUid();
21060        if (callingUid != Process.SYSTEM_UID) {
21061            throw new SecurityException(
21062                    "clearPackagePersistentPreferredActivities can only be run by the system");
21063        }
21064        ArrayList<PersistentPreferredActivity> removed = null;
21065        boolean changed = false;
21066        synchronized (mPackages) {
21067            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21068                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21069                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21070                        .valueAt(i);
21071                if (userId != thisUserId) {
21072                    continue;
21073                }
21074                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21075                while (it.hasNext()) {
21076                    PersistentPreferredActivity ppa = it.next();
21077                    // Mark entry for removal only if it matches the package name.
21078                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21079                        if (removed == null) {
21080                            removed = new ArrayList<PersistentPreferredActivity>();
21081                        }
21082                        removed.add(ppa);
21083                    }
21084                }
21085                if (removed != null) {
21086                    for (int j=0; j<removed.size(); j++) {
21087                        PersistentPreferredActivity ppa = removed.get(j);
21088                        ppir.removeFilter(ppa);
21089                    }
21090                    changed = true;
21091                }
21092            }
21093
21094            if (changed) {
21095                scheduleWritePackageRestrictionsLocked(userId);
21096                postPreferredActivityChangedBroadcast(userId);
21097            }
21098        }
21099    }
21100
21101    /**
21102     * Common machinery for picking apart a restored XML blob and passing
21103     * it to a caller-supplied functor to be applied to the running system.
21104     */
21105    private void restoreFromXml(XmlPullParser parser, int userId,
21106            String expectedStartTag, BlobXmlRestorer functor)
21107            throws IOException, XmlPullParserException {
21108        int type;
21109        while ((type = parser.next()) != XmlPullParser.START_TAG
21110                && type != XmlPullParser.END_DOCUMENT) {
21111        }
21112        if (type != XmlPullParser.START_TAG) {
21113            // oops didn't find a start tag?!
21114            if (DEBUG_BACKUP) {
21115                Slog.e(TAG, "Didn't find start tag during restore");
21116            }
21117            return;
21118        }
21119Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21120        // this is supposed to be TAG_PREFERRED_BACKUP
21121        if (!expectedStartTag.equals(parser.getName())) {
21122            if (DEBUG_BACKUP) {
21123                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21124            }
21125            return;
21126        }
21127
21128        // skip interfering stuff, then we're aligned with the backing implementation
21129        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21130Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21131        functor.apply(parser, userId);
21132    }
21133
21134    private interface BlobXmlRestorer {
21135        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21136    }
21137
21138    /**
21139     * Non-Binder method, support for the backup/restore mechanism: write the
21140     * full set of preferred activities in its canonical XML format.  Returns the
21141     * XML output as a byte array, or null if there is none.
21142     */
21143    @Override
21144    public byte[] getPreferredActivityBackup(int userId) {
21145        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21146            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21147        }
21148
21149        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21150        try {
21151            final XmlSerializer serializer = new FastXmlSerializer();
21152            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21153            serializer.startDocument(null, true);
21154            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21155
21156            synchronized (mPackages) {
21157                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21158            }
21159
21160            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21161            serializer.endDocument();
21162            serializer.flush();
21163        } catch (Exception e) {
21164            if (DEBUG_BACKUP) {
21165                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21166            }
21167            return null;
21168        }
21169
21170        return dataStream.toByteArray();
21171    }
21172
21173    @Override
21174    public void restorePreferredActivities(byte[] backup, int userId) {
21175        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21176            throw new SecurityException("Only the system may call restorePreferredActivities()");
21177        }
21178
21179        try {
21180            final XmlPullParser parser = Xml.newPullParser();
21181            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21182            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21183                    new BlobXmlRestorer() {
21184                        @Override
21185                        public void apply(XmlPullParser parser, int userId)
21186                                throws XmlPullParserException, IOException {
21187                            synchronized (mPackages) {
21188                                mSettings.readPreferredActivitiesLPw(parser, userId);
21189                            }
21190                        }
21191                    } );
21192        } catch (Exception e) {
21193            if (DEBUG_BACKUP) {
21194                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21195            }
21196        }
21197    }
21198
21199    /**
21200     * Non-Binder method, support for the backup/restore mechanism: write the
21201     * default browser (etc) settings in its canonical XML format.  Returns the default
21202     * browser XML representation as a byte array, or null if there is none.
21203     */
21204    @Override
21205    public byte[] getDefaultAppsBackup(int userId) {
21206        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21207            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21208        }
21209
21210        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21211        try {
21212            final XmlSerializer serializer = new FastXmlSerializer();
21213            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21214            serializer.startDocument(null, true);
21215            serializer.startTag(null, TAG_DEFAULT_APPS);
21216
21217            synchronized (mPackages) {
21218                mSettings.writeDefaultAppsLPr(serializer, userId);
21219            }
21220
21221            serializer.endTag(null, TAG_DEFAULT_APPS);
21222            serializer.endDocument();
21223            serializer.flush();
21224        } catch (Exception e) {
21225            if (DEBUG_BACKUP) {
21226                Slog.e(TAG, "Unable to write default apps for backup", e);
21227            }
21228            return null;
21229        }
21230
21231        return dataStream.toByteArray();
21232    }
21233
21234    @Override
21235    public void restoreDefaultApps(byte[] backup, int userId) {
21236        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21237            throw new SecurityException("Only the system may call restoreDefaultApps()");
21238        }
21239
21240        try {
21241            final XmlPullParser parser = Xml.newPullParser();
21242            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21243            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21244                    new BlobXmlRestorer() {
21245                        @Override
21246                        public void apply(XmlPullParser parser, int userId)
21247                                throws XmlPullParserException, IOException {
21248                            synchronized (mPackages) {
21249                                mSettings.readDefaultAppsLPw(parser, userId);
21250                            }
21251                        }
21252                    } );
21253        } catch (Exception e) {
21254            if (DEBUG_BACKUP) {
21255                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21256            }
21257        }
21258    }
21259
21260    @Override
21261    public byte[] getIntentFilterVerificationBackup(int userId) {
21262        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21263            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21264        }
21265
21266        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21267        try {
21268            final XmlSerializer serializer = new FastXmlSerializer();
21269            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21270            serializer.startDocument(null, true);
21271            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21272
21273            synchronized (mPackages) {
21274                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21275            }
21276
21277            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21278            serializer.endDocument();
21279            serializer.flush();
21280        } catch (Exception e) {
21281            if (DEBUG_BACKUP) {
21282                Slog.e(TAG, "Unable to write default apps for backup", e);
21283            }
21284            return null;
21285        }
21286
21287        return dataStream.toByteArray();
21288    }
21289
21290    @Override
21291    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21292        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21293            throw new SecurityException("Only the system may call restorePreferredActivities()");
21294        }
21295
21296        try {
21297            final XmlPullParser parser = Xml.newPullParser();
21298            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21299            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21300                    new BlobXmlRestorer() {
21301                        @Override
21302                        public void apply(XmlPullParser parser, int userId)
21303                                throws XmlPullParserException, IOException {
21304                            synchronized (mPackages) {
21305                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21306                                mSettings.writeLPr();
21307                            }
21308                        }
21309                    } );
21310        } catch (Exception e) {
21311            if (DEBUG_BACKUP) {
21312                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21313            }
21314        }
21315    }
21316
21317    @Override
21318    public byte[] getPermissionGrantBackup(int userId) {
21319        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21320            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21321        }
21322
21323        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21324        try {
21325            final XmlSerializer serializer = new FastXmlSerializer();
21326            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21327            serializer.startDocument(null, true);
21328            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21329
21330            synchronized (mPackages) {
21331                serializeRuntimePermissionGrantsLPr(serializer, userId);
21332            }
21333
21334            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21335            serializer.endDocument();
21336            serializer.flush();
21337        } catch (Exception e) {
21338            if (DEBUG_BACKUP) {
21339                Slog.e(TAG, "Unable to write default apps for backup", e);
21340            }
21341            return null;
21342        }
21343
21344        return dataStream.toByteArray();
21345    }
21346
21347    @Override
21348    public void restorePermissionGrants(byte[] backup, int userId) {
21349        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21350            throw new SecurityException("Only the system may call restorePermissionGrants()");
21351        }
21352
21353        try {
21354            final XmlPullParser parser = Xml.newPullParser();
21355            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21356            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21357                    new BlobXmlRestorer() {
21358                        @Override
21359                        public void apply(XmlPullParser parser, int userId)
21360                                throws XmlPullParserException, IOException {
21361                            synchronized (mPackages) {
21362                                processRestoredPermissionGrantsLPr(parser, userId);
21363                            }
21364                        }
21365                    } );
21366        } catch (Exception e) {
21367            if (DEBUG_BACKUP) {
21368                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21369            }
21370        }
21371    }
21372
21373    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21374            throws IOException {
21375        serializer.startTag(null, TAG_ALL_GRANTS);
21376
21377        final int N = mSettings.mPackages.size();
21378        for (int i = 0; i < N; i++) {
21379            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21380            boolean pkgGrantsKnown = false;
21381
21382            PermissionsState packagePerms = ps.getPermissionsState();
21383
21384            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21385                final int grantFlags = state.getFlags();
21386                // only look at grants that are not system/policy fixed
21387                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21388                    final boolean isGranted = state.isGranted();
21389                    // And only back up the user-twiddled state bits
21390                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21391                        final String packageName = mSettings.mPackages.keyAt(i);
21392                        if (!pkgGrantsKnown) {
21393                            serializer.startTag(null, TAG_GRANT);
21394                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21395                            pkgGrantsKnown = true;
21396                        }
21397
21398                        final boolean userSet =
21399                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21400                        final boolean userFixed =
21401                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21402                        final boolean revoke =
21403                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21404
21405                        serializer.startTag(null, TAG_PERMISSION);
21406                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21407                        if (isGranted) {
21408                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21409                        }
21410                        if (userSet) {
21411                            serializer.attribute(null, ATTR_USER_SET, "true");
21412                        }
21413                        if (userFixed) {
21414                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21415                        }
21416                        if (revoke) {
21417                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21418                        }
21419                        serializer.endTag(null, TAG_PERMISSION);
21420                    }
21421                }
21422            }
21423
21424            if (pkgGrantsKnown) {
21425                serializer.endTag(null, TAG_GRANT);
21426            }
21427        }
21428
21429        serializer.endTag(null, TAG_ALL_GRANTS);
21430    }
21431
21432    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21433            throws XmlPullParserException, IOException {
21434        String pkgName = null;
21435        int outerDepth = parser.getDepth();
21436        int type;
21437        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21438                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21439            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21440                continue;
21441            }
21442
21443            final String tagName = parser.getName();
21444            if (tagName.equals(TAG_GRANT)) {
21445                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21446                if (DEBUG_BACKUP) {
21447                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21448                }
21449            } else if (tagName.equals(TAG_PERMISSION)) {
21450
21451                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21452                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21453
21454                int newFlagSet = 0;
21455                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21456                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21457                }
21458                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21459                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21460                }
21461                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21462                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21463                }
21464                if (DEBUG_BACKUP) {
21465                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21466                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21467                }
21468                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21469                if (ps != null) {
21470                    // Already installed so we apply the grant immediately
21471                    if (DEBUG_BACKUP) {
21472                        Slog.v(TAG, "        + already installed; applying");
21473                    }
21474                    PermissionsState perms = ps.getPermissionsState();
21475                    BasePermission bp = mSettings.mPermissions.get(permName);
21476                    if (bp != null) {
21477                        if (isGranted) {
21478                            perms.grantRuntimePermission(bp, userId);
21479                        }
21480                        if (newFlagSet != 0) {
21481                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21482                        }
21483                    }
21484                } else {
21485                    // Need to wait for post-restore install to apply the grant
21486                    if (DEBUG_BACKUP) {
21487                        Slog.v(TAG, "        - not yet installed; saving for later");
21488                    }
21489                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21490                            isGranted, newFlagSet, userId);
21491                }
21492            } else {
21493                PackageManagerService.reportSettingsProblem(Log.WARN,
21494                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21495                XmlUtils.skipCurrentTag(parser);
21496            }
21497        }
21498
21499        scheduleWriteSettingsLocked();
21500        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21501    }
21502
21503    @Override
21504    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21505            int sourceUserId, int targetUserId, int flags) {
21506        mContext.enforceCallingOrSelfPermission(
21507                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21508        int callingUid = Binder.getCallingUid();
21509        enforceOwnerRights(ownerPackage, callingUid);
21510        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21511        if (intentFilter.countActions() == 0) {
21512            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21513            return;
21514        }
21515        synchronized (mPackages) {
21516            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21517                    ownerPackage, targetUserId, flags);
21518            CrossProfileIntentResolver resolver =
21519                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21520            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21521            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21522            if (existing != null) {
21523                int size = existing.size();
21524                for (int i = 0; i < size; i++) {
21525                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21526                        return;
21527                    }
21528                }
21529            }
21530            resolver.addFilter(newFilter);
21531            scheduleWritePackageRestrictionsLocked(sourceUserId);
21532        }
21533    }
21534
21535    @Override
21536    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21537        mContext.enforceCallingOrSelfPermission(
21538                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21539        final int callingUid = Binder.getCallingUid();
21540        enforceOwnerRights(ownerPackage, callingUid);
21541        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21542        synchronized (mPackages) {
21543            CrossProfileIntentResolver resolver =
21544                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21545            ArraySet<CrossProfileIntentFilter> set =
21546                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21547            for (CrossProfileIntentFilter filter : set) {
21548                if (filter.getOwnerPackage().equals(ownerPackage)) {
21549                    resolver.removeFilter(filter);
21550                }
21551            }
21552            scheduleWritePackageRestrictionsLocked(sourceUserId);
21553        }
21554    }
21555
21556    // Enforcing that callingUid is owning pkg on userId
21557    private void enforceOwnerRights(String pkg, int callingUid) {
21558        // The system owns everything.
21559        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21560            return;
21561        }
21562        final int callingUserId = UserHandle.getUserId(callingUid);
21563        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21564        if (pi == null) {
21565            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21566                    + callingUserId);
21567        }
21568        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21569            throw new SecurityException("Calling uid " + callingUid
21570                    + " does not own package " + pkg);
21571        }
21572    }
21573
21574    @Override
21575    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21576        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21577            return null;
21578        }
21579        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21580    }
21581
21582    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21583        UserManagerService ums = UserManagerService.getInstance();
21584        if (ums != null) {
21585            final UserInfo parent = ums.getProfileParent(userId);
21586            final int launcherUid = (parent != null) ? parent.id : userId;
21587            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21588            if (launcherComponent != null) {
21589                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21590                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21591                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21592                        .setPackage(launcherComponent.getPackageName());
21593                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21594            }
21595        }
21596    }
21597
21598    /**
21599     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21600     * then reports the most likely home activity or null if there are more than one.
21601     */
21602    private ComponentName getDefaultHomeActivity(int userId) {
21603        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21604        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21605        if (cn != null) {
21606            return cn;
21607        }
21608
21609        // Find the launcher with the highest priority and return that component if there are no
21610        // other home activity with the same priority.
21611        int lastPriority = Integer.MIN_VALUE;
21612        ComponentName lastComponent = null;
21613        final int size = allHomeCandidates.size();
21614        for (int i = 0; i < size; i++) {
21615            final ResolveInfo ri = allHomeCandidates.get(i);
21616            if (ri.priority > lastPriority) {
21617                lastComponent = ri.activityInfo.getComponentName();
21618                lastPriority = ri.priority;
21619            } else if (ri.priority == lastPriority) {
21620                // Two components found with same priority.
21621                lastComponent = null;
21622            }
21623        }
21624        return lastComponent;
21625    }
21626
21627    private Intent getHomeIntent() {
21628        Intent intent = new Intent(Intent.ACTION_MAIN);
21629        intent.addCategory(Intent.CATEGORY_HOME);
21630        intent.addCategory(Intent.CATEGORY_DEFAULT);
21631        return intent;
21632    }
21633
21634    private IntentFilter getHomeFilter() {
21635        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21636        filter.addCategory(Intent.CATEGORY_HOME);
21637        filter.addCategory(Intent.CATEGORY_DEFAULT);
21638        return filter;
21639    }
21640
21641    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21642            int userId) {
21643        Intent intent  = getHomeIntent();
21644        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21645                PackageManager.GET_META_DATA, userId);
21646        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21647                true, false, false, userId);
21648
21649        allHomeCandidates.clear();
21650        if (list != null) {
21651            for (ResolveInfo ri : list) {
21652                allHomeCandidates.add(ri);
21653            }
21654        }
21655        return (preferred == null || preferred.activityInfo == null)
21656                ? null
21657                : new ComponentName(preferred.activityInfo.packageName,
21658                        preferred.activityInfo.name);
21659    }
21660
21661    @Override
21662    public void setHomeActivity(ComponentName comp, int userId) {
21663        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21664            return;
21665        }
21666        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21667        getHomeActivitiesAsUser(homeActivities, userId);
21668
21669        boolean found = false;
21670
21671        final int size = homeActivities.size();
21672        final ComponentName[] set = new ComponentName[size];
21673        for (int i = 0; i < size; i++) {
21674            final ResolveInfo candidate = homeActivities.get(i);
21675            final ActivityInfo info = candidate.activityInfo;
21676            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21677            set[i] = activityName;
21678            if (!found && activityName.equals(comp)) {
21679                found = true;
21680            }
21681        }
21682        if (!found) {
21683            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21684                    + userId);
21685        }
21686        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21687                set, comp, userId);
21688    }
21689
21690    private @Nullable String getSetupWizardPackageName() {
21691        final Intent intent = new Intent(Intent.ACTION_MAIN);
21692        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21693
21694        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21695                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21696                        | MATCH_DISABLED_COMPONENTS,
21697                UserHandle.myUserId());
21698        if (matches.size() == 1) {
21699            return matches.get(0).getComponentInfo().packageName;
21700        } else {
21701            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21702                    + ": matches=" + matches);
21703            return null;
21704        }
21705    }
21706
21707    private @Nullable String getStorageManagerPackageName() {
21708        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21709
21710        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21711                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21712                        | MATCH_DISABLED_COMPONENTS,
21713                UserHandle.myUserId());
21714        if (matches.size() == 1) {
21715            return matches.get(0).getComponentInfo().packageName;
21716        } else {
21717            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21718                    + matches.size() + ": matches=" + matches);
21719            return null;
21720        }
21721    }
21722
21723    @Override
21724    public void setApplicationEnabledSetting(String appPackageName,
21725            int newState, int flags, int userId, String callingPackage) {
21726        if (!sUserManager.exists(userId)) return;
21727        if (callingPackage == null) {
21728            callingPackage = Integer.toString(Binder.getCallingUid());
21729        }
21730        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21731    }
21732
21733    @Override
21734    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21735        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21736        synchronized (mPackages) {
21737            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21738            if (pkgSetting != null) {
21739                pkgSetting.setUpdateAvailable(updateAvailable);
21740            }
21741        }
21742    }
21743
21744    @Override
21745    public void setComponentEnabledSetting(ComponentName componentName,
21746            int newState, int flags, int userId) {
21747        if (!sUserManager.exists(userId)) return;
21748        setEnabledSetting(componentName.getPackageName(),
21749                componentName.getClassName(), newState, flags, userId, null);
21750    }
21751
21752    private void setEnabledSetting(final String packageName, String className, int newState,
21753            final int flags, int userId, String callingPackage) {
21754        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21755              || newState == COMPONENT_ENABLED_STATE_ENABLED
21756              || newState == COMPONENT_ENABLED_STATE_DISABLED
21757              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21758              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21759            throw new IllegalArgumentException("Invalid new component state: "
21760                    + newState);
21761        }
21762        PackageSetting pkgSetting;
21763        final int callingUid = Binder.getCallingUid();
21764        final int permission;
21765        if (callingUid == Process.SYSTEM_UID) {
21766            permission = PackageManager.PERMISSION_GRANTED;
21767        } else {
21768            permission = mContext.checkCallingOrSelfPermission(
21769                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21770        }
21771        enforceCrossUserPermission(callingUid, userId,
21772                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21773        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21774        boolean sendNow = false;
21775        boolean isApp = (className == null);
21776        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21777        String componentName = isApp ? packageName : className;
21778        int packageUid = -1;
21779        ArrayList<String> components;
21780
21781        // reader
21782        synchronized (mPackages) {
21783            pkgSetting = mSettings.mPackages.get(packageName);
21784            if (pkgSetting == null) {
21785                if (!isCallerInstantApp) {
21786                    if (className == null) {
21787                        throw new IllegalArgumentException("Unknown package: " + packageName);
21788                    }
21789                    throw new IllegalArgumentException(
21790                            "Unknown component: " + packageName + "/" + className);
21791                } else {
21792                    // throw SecurityException to prevent leaking package information
21793                    throw new SecurityException(
21794                            "Attempt to change component state; "
21795                            + "pid=" + Binder.getCallingPid()
21796                            + ", uid=" + callingUid
21797                            + (className == null
21798                                    ? ", package=" + packageName
21799                                    : ", component=" + packageName + "/" + className));
21800                }
21801            }
21802        }
21803
21804        // Limit who can change which apps
21805        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21806            // Don't allow apps that don't have permission to modify other apps
21807            if (!allowedByPermission
21808                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21809                throw new SecurityException(
21810                        "Attempt to change component state; "
21811                        + "pid=" + Binder.getCallingPid()
21812                        + ", uid=" + callingUid
21813                        + (className == null
21814                                ? ", package=" + packageName
21815                                : ", component=" + packageName + "/" + className));
21816            }
21817            // Don't allow changing protected packages.
21818            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21819                throw new SecurityException("Cannot disable a protected package: " + packageName);
21820            }
21821        }
21822
21823        if (callingUid == Process.SHELL_UID
21824                && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21825            // Shell can only change whole packages between ENABLED and DISABLED_USER states
21826            // unless it is a test package.
21827            int oldState = pkgSetting.getEnabled(userId);
21828            if (className == null
21829                &&
21830                (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21831                 || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21832                 || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21833                &&
21834                (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21835                 || newState == COMPONENT_ENABLED_STATE_DEFAULT
21836                 || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21837                // ok
21838            } else {
21839                throw new SecurityException(
21840                        "Shell cannot change component state for " + packageName + "/"
21841                        + className + " to " + newState);
21842            }
21843        }
21844        if (className == null) {
21845            // We're dealing with an application/package level state change
21846            if (pkgSetting.getEnabled(userId) == newState) {
21847                // Nothing to do
21848                return;
21849            }
21850            // If we're enabling a system stub, there's a little more work to do.
21851            // Prior to enabling the package, we need to decompress the APK(s) to the
21852            // data partition and then replace the version on the system partition.
21853            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21854            final boolean isSystemStub = deletedPkg.isStub
21855                    && deletedPkg.isSystemApp();
21856            if (isSystemStub
21857                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21858                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21859                final File codePath = decompressPackage(deletedPkg);
21860                if (codePath == null) {
21861                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21862                    return;
21863                }
21864                // TODO remove direct parsing of the package object during internal cleanup
21865                // of scan package
21866                // We need to call parse directly here for no other reason than we need
21867                // the new package in order to disable the old one [we use the information
21868                // for some internal optimization to optionally create a new package setting
21869                // object on replace]. However, we can't get the package from the scan
21870                // because the scan modifies live structures and we need to remove the
21871                // old [system] package from the system before a scan can be attempted.
21872                // Once scan is indempotent we can remove this parse and use the package
21873                // object we scanned, prior to adding it to package settings.
21874                final PackageParser pp = new PackageParser();
21875                pp.setSeparateProcesses(mSeparateProcesses);
21876                pp.setDisplayMetrics(mMetrics);
21877                pp.setCallback(mPackageParserCallback);
21878                final PackageParser.Package tmpPkg;
21879                try {
21880                    final int parseFlags = mDefParseFlags
21881                            | PackageParser.PARSE_MUST_BE_APK
21882                            | PackageParser.PARSE_IS_SYSTEM
21883                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21884                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21885                } catch (PackageParserException e) {
21886                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21887                    return;
21888                }
21889                synchronized (mInstallLock) {
21890                    // Disable the stub and remove any package entries
21891                    removePackageLI(deletedPkg, true);
21892                    synchronized (mPackages) {
21893                        disableSystemPackageLPw(deletedPkg, tmpPkg);
21894                    }
21895                    final PackageParser.Package newPkg;
21896                    try (PackageFreezer freezer =
21897                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21898                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
21899                                | PackageParser.PARSE_ENFORCE_CODE;
21900                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
21901                                0 /*currentTime*/, null /*user*/);
21902                        prepareAppDataAfterInstallLIF(newPkg);
21903                        synchronized (mPackages) {
21904                            try {
21905                                updateSharedLibrariesLPr(newPkg, null);
21906                            } catch (PackageManagerException e) {
21907                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
21908                            }
21909                            updatePermissionsLPw(newPkg.packageName, newPkg,
21910                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
21911                            mSettings.writeLPr();
21912                        }
21913                    } catch (PackageManagerException e) {
21914                        // Whoops! Something went wrong; try to roll back to the stub
21915                        Slog.w(TAG, "Failed to install compressed system package:"
21916                                + pkgSetting.name, e);
21917                        // Remove the failed install
21918                        removeCodePathLI(codePath);
21919
21920                        // Install the system package
21921                        try (PackageFreezer freezer =
21922                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21923                            synchronized (mPackages) {
21924                                // NOTE: The system package always needs to be enabled; even
21925                                // if it's for a compressed stub. If we don't, installing the
21926                                // system package fails during scan [scanning checks the disabled
21927                                // packages]. We will reverse this later, after we've "installed"
21928                                // the stub.
21929                                // This leaves us in a fragile state; the stub should never be
21930                                // enabled, so, cross your fingers and hope nothing goes wrong
21931                                // until we can disable the package later.
21932                                enableSystemPackageLPw(deletedPkg);
21933                            }
21934                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
21935                                    false /*isPrivileged*/, null /*allUserHandles*/,
21936                                    null /*origUserHandles*/, null /*origPermissionsState*/,
21937                                    true /*writeSettings*/);
21938                        } catch (PackageManagerException pme) {
21939                            Slog.w(TAG, "Failed to restore system package:"
21940                                    + deletedPkg.packageName, pme);
21941                        } finally {
21942                            synchronized (mPackages) {
21943                                mSettings.disableSystemPackageLPw(
21944                                        deletedPkg.packageName, true /*replaced*/);
21945                                mSettings.writeLPr();
21946                            }
21947                        }
21948                        return;
21949                    }
21950                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
21951                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21952                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
21953                    mDexManager.notifyPackageUpdated(newPkg.packageName,
21954                            newPkg.baseCodePath, newPkg.splitCodePaths);
21955                }
21956            }
21957            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21958                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21959                // Don't care about who enables an app.
21960                callingPackage = null;
21961            }
21962            pkgSetting.setEnabled(newState, userId, callingPackage);
21963        } else {
21964            // We're dealing with a component level state change
21965            // First, verify that this is a valid class name.
21966            PackageParser.Package pkg = pkgSetting.pkg;
21967            if (pkg == null || !pkg.hasComponentClassName(className)) {
21968                if (pkg != null &&
21969                        pkg.applicationInfo.targetSdkVersion >=
21970                                Build.VERSION_CODES.JELLY_BEAN) {
21971                    throw new IllegalArgumentException("Component class " + className
21972                            + " does not exist in " + packageName);
21973                } else {
21974                    Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21975                            + className + " does not exist in " + packageName);
21976                }
21977            }
21978            switch (newState) {
21979            case COMPONENT_ENABLED_STATE_ENABLED:
21980                if (!pkgSetting.enableComponentLPw(className, userId)) {
21981                    return;
21982                }
21983                break;
21984            case COMPONENT_ENABLED_STATE_DISABLED:
21985                if (!pkgSetting.disableComponentLPw(className, userId)) {
21986                    return;
21987                }
21988                break;
21989            case COMPONENT_ENABLED_STATE_DEFAULT:
21990                if (!pkgSetting.restoreComponentLPw(className, userId)) {
21991                    return;
21992                }
21993                break;
21994            default:
21995                Slog.e(TAG, "Invalid new component state: " + newState);
21996                return;
21997            }
21998        }
21999        synchronized (mPackages) {
22000            scheduleWritePackageRestrictionsLocked(userId);
22001            updateSequenceNumberLP(pkgSetting, new int[] { userId });
22002            final long callingId = Binder.clearCallingIdentity();
22003            try {
22004                updateInstantAppInstallerLocked(packageName);
22005            } finally {
22006                Binder.restoreCallingIdentity(callingId);
22007            }
22008            components = mPendingBroadcasts.get(userId, packageName);
22009            final boolean newPackage = components == null;
22010            if (newPackage) {
22011                components = new ArrayList<String>();
22012            }
22013            if (!components.contains(componentName)) {
22014                components.add(componentName);
22015            }
22016            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
22017                sendNow = true;
22018                // Purge entry from pending broadcast list if another one exists already
22019                // since we are sending one right away.
22020                mPendingBroadcasts.remove(userId, packageName);
22021            } else {
22022                if (newPackage) {
22023                    mPendingBroadcasts.put(userId, packageName, components);
22024                }
22025                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
22026                    // Schedule a message
22027                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
22028                }
22029            }
22030        }
22031
22032        long callingId = Binder.clearCallingIdentity();
22033        try {
22034            if (sendNow) {
22035                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
22036                sendPackageChangedBroadcast(packageName,
22037                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
22038            }
22039        } finally {
22040            Binder.restoreCallingIdentity(callingId);
22041        }
22042    }
22043
22044    @Override
22045    public void flushPackageRestrictionsAsUser(int userId) {
22046        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22047            return;
22048        }
22049        if (!sUserManager.exists(userId)) {
22050            return;
22051        }
22052        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
22053                false /* checkShell */, "flushPackageRestrictions");
22054        synchronized (mPackages) {
22055            mSettings.writePackageRestrictionsLPr(userId);
22056            mDirtyUsers.remove(userId);
22057            if (mDirtyUsers.isEmpty()) {
22058                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
22059            }
22060        }
22061    }
22062
22063    private void sendPackageChangedBroadcast(String packageName,
22064            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
22065        if (DEBUG_INSTALL)
22066            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
22067                    + componentNames);
22068        Bundle extras = new Bundle(4);
22069        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
22070        String nameList[] = new String[componentNames.size()];
22071        componentNames.toArray(nameList);
22072        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
22073        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
22074        extras.putInt(Intent.EXTRA_UID, packageUid);
22075        // If this is not reporting a change of the overall package, then only send it
22076        // to registered receivers.  We don't want to launch a swath of apps for every
22077        // little component state change.
22078        final int flags = !componentNames.contains(packageName)
22079                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
22080        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
22081                new int[] {UserHandle.getUserId(packageUid)});
22082    }
22083
22084    @Override
22085    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
22086        if (!sUserManager.exists(userId)) return;
22087        final int callingUid = Binder.getCallingUid();
22088        if (getInstantAppPackageName(callingUid) != null) {
22089            return;
22090        }
22091        final int permission = mContext.checkCallingOrSelfPermission(
22092                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
22093        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
22094        enforceCrossUserPermission(callingUid, userId,
22095                true /* requireFullPermission */, true /* checkShell */, "stop package");
22096        // writer
22097        synchronized (mPackages) {
22098            final PackageSetting ps = mSettings.mPackages.get(packageName);
22099            if (!filterAppAccessLPr(ps, callingUid, userId)
22100                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
22101                            allowedByPermission, callingUid, userId)) {
22102                scheduleWritePackageRestrictionsLocked(userId);
22103            }
22104        }
22105    }
22106
22107    @Override
22108    public String getInstallerPackageName(String packageName) {
22109        final int callingUid = Binder.getCallingUid();
22110        if (getInstantAppPackageName(callingUid) != null) {
22111            return null;
22112        }
22113        // reader
22114        synchronized (mPackages) {
22115            final PackageSetting ps = mSettings.mPackages.get(packageName);
22116            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
22117                return null;
22118            }
22119            return mSettings.getInstallerPackageNameLPr(packageName);
22120        }
22121    }
22122
22123    public boolean isOrphaned(String packageName) {
22124        // reader
22125        synchronized (mPackages) {
22126            return mSettings.isOrphaned(packageName);
22127        }
22128    }
22129
22130    @Override
22131    public int getApplicationEnabledSetting(String packageName, int userId) {
22132        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22133        int callingUid = Binder.getCallingUid();
22134        enforceCrossUserPermission(callingUid, userId,
22135                false /* requireFullPermission */, false /* checkShell */, "get enabled");
22136        // reader
22137        synchronized (mPackages) {
22138            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22139                return COMPONENT_ENABLED_STATE_DISABLED;
22140            }
22141            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22142        }
22143    }
22144
22145    @Override
22146    public int getComponentEnabledSetting(ComponentName component, int userId) {
22147        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22148        int callingUid = Binder.getCallingUid();
22149        enforceCrossUserPermission(callingUid, userId,
22150                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22151        synchronized (mPackages) {
22152            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22153                    component, TYPE_UNKNOWN, userId)) {
22154                return COMPONENT_ENABLED_STATE_DISABLED;
22155            }
22156            return mSettings.getComponentEnabledSettingLPr(component, userId);
22157        }
22158    }
22159
22160    @Override
22161    public void enterSafeMode() {
22162        enforceSystemOrRoot("Only the system can request entering safe mode");
22163
22164        if (!mSystemReady) {
22165            mSafeMode = true;
22166        }
22167    }
22168
22169    @Override
22170    public void systemReady() {
22171        enforceSystemOrRoot("Only the system can claim the system is ready");
22172
22173        mSystemReady = true;
22174        final ContentResolver resolver = mContext.getContentResolver();
22175        ContentObserver co = new ContentObserver(mHandler) {
22176            @Override
22177            public void onChange(boolean selfChange) {
22178                mEphemeralAppsDisabled =
22179                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22180                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22181            }
22182        };
22183        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22184                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22185                false, co, UserHandle.USER_SYSTEM);
22186        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22187                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22188        co.onChange(true);
22189
22190        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22191        // disabled after already being started.
22192        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22193                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22194
22195        // Read the compatibilty setting when the system is ready.
22196        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22197                mContext.getContentResolver(),
22198                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22199        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22200        if (DEBUG_SETTINGS) {
22201            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22202        }
22203
22204        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22205
22206        synchronized (mPackages) {
22207            // Verify that all of the preferred activity components actually
22208            // exist.  It is possible for applications to be updated and at
22209            // that point remove a previously declared activity component that
22210            // had been set as a preferred activity.  We try to clean this up
22211            // the next time we encounter that preferred activity, but it is
22212            // possible for the user flow to never be able to return to that
22213            // situation so here we do a sanity check to make sure we haven't
22214            // left any junk around.
22215            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22216            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22217                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22218                removed.clear();
22219                for (PreferredActivity pa : pir.filterSet()) {
22220                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22221                        removed.add(pa);
22222                    }
22223                }
22224                if (removed.size() > 0) {
22225                    for (int r=0; r<removed.size(); r++) {
22226                        PreferredActivity pa = removed.get(r);
22227                        Slog.w(TAG, "Removing dangling preferred activity: "
22228                                + pa.mPref.mComponent);
22229                        pir.removeFilter(pa);
22230                    }
22231                    mSettings.writePackageRestrictionsLPr(
22232                            mSettings.mPreferredActivities.keyAt(i));
22233                }
22234            }
22235
22236            for (int userId : UserManagerService.getInstance().getUserIds()) {
22237                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22238                    grantPermissionsUserIds = ArrayUtils.appendInt(
22239                            grantPermissionsUserIds, userId);
22240                }
22241            }
22242        }
22243        sUserManager.systemReady();
22244
22245        // If we upgraded grant all default permissions before kicking off.
22246        for (int userId : grantPermissionsUserIds) {
22247            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22248        }
22249
22250        // If we did not grant default permissions, we preload from this the
22251        // default permission exceptions lazily to ensure we don't hit the
22252        // disk on a new user creation.
22253        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22254            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22255        }
22256
22257        // Kick off any messages waiting for system ready
22258        if (mPostSystemReadyMessages != null) {
22259            for (Message msg : mPostSystemReadyMessages) {
22260                msg.sendToTarget();
22261            }
22262            mPostSystemReadyMessages = null;
22263        }
22264
22265        // Watch for external volumes that come and go over time
22266        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22267        storage.registerListener(mStorageListener);
22268
22269        mInstallerService.systemReady();
22270        mPackageDexOptimizer.systemReady();
22271
22272        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22273                StorageManagerInternal.class);
22274        StorageManagerInternal.addExternalStoragePolicy(
22275                new StorageManagerInternal.ExternalStorageMountPolicy() {
22276            @Override
22277            public int getMountMode(int uid, String packageName) {
22278                if (Process.isIsolated(uid)) {
22279                    return Zygote.MOUNT_EXTERNAL_NONE;
22280                }
22281                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22282                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22283                }
22284                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22285                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22286                }
22287                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22288                    return Zygote.MOUNT_EXTERNAL_READ;
22289                }
22290                return Zygote.MOUNT_EXTERNAL_WRITE;
22291            }
22292
22293            @Override
22294            public boolean hasExternalStorage(int uid, String packageName) {
22295                return true;
22296            }
22297        });
22298
22299        // Now that we're mostly running, clean up stale users and apps
22300        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22301        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22302
22303        if (mPrivappPermissionsViolations != null) {
22304            Slog.wtf(TAG,"Signature|privileged permissions not in "
22305                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22306            mPrivappPermissionsViolations = null;
22307        }
22308    }
22309
22310    public void waitForAppDataPrepared() {
22311        if (mPrepareAppDataFuture == null) {
22312            return;
22313        }
22314        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22315        mPrepareAppDataFuture = null;
22316    }
22317
22318    @Override
22319    public boolean isSafeMode() {
22320        // allow instant applications
22321        return mSafeMode;
22322    }
22323
22324    @Override
22325    public boolean hasSystemUidErrors() {
22326        // allow instant applications
22327        return mHasSystemUidErrors;
22328    }
22329
22330    static String arrayToString(int[] array) {
22331        StringBuffer buf = new StringBuffer(128);
22332        buf.append('[');
22333        if (array != null) {
22334            for (int i=0; i<array.length; i++) {
22335                if (i > 0) buf.append(", ");
22336                buf.append(array[i]);
22337            }
22338        }
22339        buf.append(']');
22340        return buf.toString();
22341    }
22342
22343    static class DumpState {
22344        public static final int DUMP_LIBS = 1 << 0;
22345        public static final int DUMP_FEATURES = 1 << 1;
22346        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22347        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22348        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22349        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22350        public static final int DUMP_PERMISSIONS = 1 << 6;
22351        public static final int DUMP_PACKAGES = 1 << 7;
22352        public static final int DUMP_SHARED_USERS = 1 << 8;
22353        public static final int DUMP_MESSAGES = 1 << 9;
22354        public static final int DUMP_PROVIDERS = 1 << 10;
22355        public static final int DUMP_VERIFIERS = 1 << 11;
22356        public static final int DUMP_PREFERRED = 1 << 12;
22357        public static final int DUMP_PREFERRED_XML = 1 << 13;
22358        public static final int DUMP_KEYSETS = 1 << 14;
22359        public static final int DUMP_VERSION = 1 << 15;
22360        public static final int DUMP_INSTALLS = 1 << 16;
22361        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22362        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22363        public static final int DUMP_FROZEN = 1 << 19;
22364        public static final int DUMP_DEXOPT = 1 << 20;
22365        public static final int DUMP_COMPILER_STATS = 1 << 21;
22366        public static final int DUMP_CHANGES = 1 << 22;
22367        public static final int DUMP_VOLUMES = 1 << 23;
22368
22369        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22370
22371        private int mTypes;
22372
22373        private int mOptions;
22374
22375        private boolean mTitlePrinted;
22376
22377        private SharedUserSetting mSharedUser;
22378
22379        public boolean isDumping(int type) {
22380            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22381                return true;
22382            }
22383
22384            return (mTypes & type) != 0;
22385        }
22386
22387        public void setDump(int type) {
22388            mTypes |= type;
22389        }
22390
22391        public boolean isOptionEnabled(int option) {
22392            return (mOptions & option) != 0;
22393        }
22394
22395        public void setOptionEnabled(int option) {
22396            mOptions |= option;
22397        }
22398
22399        public boolean onTitlePrinted() {
22400            final boolean printed = mTitlePrinted;
22401            mTitlePrinted = true;
22402            return printed;
22403        }
22404
22405        public boolean getTitlePrinted() {
22406            return mTitlePrinted;
22407        }
22408
22409        public void setTitlePrinted(boolean enabled) {
22410            mTitlePrinted = enabled;
22411        }
22412
22413        public SharedUserSetting getSharedUser() {
22414            return mSharedUser;
22415        }
22416
22417        public void setSharedUser(SharedUserSetting user) {
22418            mSharedUser = user;
22419        }
22420    }
22421
22422    @Override
22423    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22424            FileDescriptor err, String[] args, ShellCallback callback,
22425            ResultReceiver resultReceiver) {
22426        (new PackageManagerShellCommand(this)).exec(
22427                this, in, out, err, args, callback, resultReceiver);
22428    }
22429
22430    @Override
22431    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22432        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22433
22434        DumpState dumpState = new DumpState();
22435        boolean fullPreferred = false;
22436        boolean checkin = false;
22437
22438        String packageName = null;
22439        ArraySet<String> permissionNames = null;
22440
22441        int opti = 0;
22442        while (opti < args.length) {
22443            String opt = args[opti];
22444            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22445                break;
22446            }
22447            opti++;
22448
22449            if ("-a".equals(opt)) {
22450                // Right now we only know how to print all.
22451            } else if ("-h".equals(opt)) {
22452                pw.println("Package manager dump options:");
22453                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22454                pw.println("    --checkin: dump for a checkin");
22455                pw.println("    -f: print details of intent filters");
22456                pw.println("    -h: print this help");
22457                pw.println("  cmd may be one of:");
22458                pw.println("    l[ibraries]: list known shared libraries");
22459                pw.println("    f[eatures]: list device features");
22460                pw.println("    k[eysets]: print known keysets");
22461                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22462                pw.println("    perm[issions]: dump permissions");
22463                pw.println("    permission [name ...]: dump declaration and use of given permission");
22464                pw.println("    pref[erred]: print preferred package settings");
22465                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22466                pw.println("    prov[iders]: dump content providers");
22467                pw.println("    p[ackages]: dump installed packages");
22468                pw.println("    s[hared-users]: dump shared user IDs");
22469                pw.println("    m[essages]: print collected runtime messages");
22470                pw.println("    v[erifiers]: print package verifier info");
22471                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22472                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22473                pw.println("    version: print database version info");
22474                pw.println("    write: write current settings now");
22475                pw.println("    installs: details about install sessions");
22476                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22477                pw.println("    dexopt: dump dexopt state");
22478                pw.println("    compiler-stats: dump compiler statistics");
22479                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22480                pw.println("    <package.name>: info about given package");
22481                return;
22482            } else if ("--checkin".equals(opt)) {
22483                checkin = true;
22484            } else if ("-f".equals(opt)) {
22485                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22486            } else if ("--proto".equals(opt)) {
22487                dumpProto(fd);
22488                return;
22489            } else {
22490                pw.println("Unknown argument: " + opt + "; use -h for help");
22491            }
22492        }
22493
22494        // Is the caller requesting to dump a particular piece of data?
22495        if (opti < args.length) {
22496            String cmd = args[opti];
22497            opti++;
22498            // Is this a package name?
22499            if ("android".equals(cmd) || cmd.contains(".")) {
22500                packageName = cmd;
22501                // When dumping a single package, we always dump all of its
22502                // filter information since the amount of data will be reasonable.
22503                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22504            } else if ("check-permission".equals(cmd)) {
22505                if (opti >= args.length) {
22506                    pw.println("Error: check-permission missing permission argument");
22507                    return;
22508                }
22509                String perm = args[opti];
22510                opti++;
22511                if (opti >= args.length) {
22512                    pw.println("Error: check-permission missing package argument");
22513                    return;
22514                }
22515
22516                String pkg = args[opti];
22517                opti++;
22518                int user = UserHandle.getUserId(Binder.getCallingUid());
22519                if (opti < args.length) {
22520                    try {
22521                        user = Integer.parseInt(args[opti]);
22522                    } catch (NumberFormatException e) {
22523                        pw.println("Error: check-permission user argument is not a number: "
22524                                + args[opti]);
22525                        return;
22526                    }
22527                }
22528
22529                // Normalize package name to handle renamed packages and static libs
22530                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22531
22532                pw.println(checkPermission(perm, pkg, user));
22533                return;
22534            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22535                dumpState.setDump(DumpState.DUMP_LIBS);
22536            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22537                dumpState.setDump(DumpState.DUMP_FEATURES);
22538            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22539                if (opti >= args.length) {
22540                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22541                            | DumpState.DUMP_SERVICE_RESOLVERS
22542                            | DumpState.DUMP_RECEIVER_RESOLVERS
22543                            | DumpState.DUMP_CONTENT_RESOLVERS);
22544                } else {
22545                    while (opti < args.length) {
22546                        String name = args[opti];
22547                        if ("a".equals(name) || "activity".equals(name)) {
22548                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22549                        } else if ("s".equals(name) || "service".equals(name)) {
22550                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22551                        } else if ("r".equals(name) || "receiver".equals(name)) {
22552                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22553                        } else if ("c".equals(name) || "content".equals(name)) {
22554                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22555                        } else {
22556                            pw.println("Error: unknown resolver table type: " + name);
22557                            return;
22558                        }
22559                        opti++;
22560                    }
22561                }
22562            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22563                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22564            } else if ("permission".equals(cmd)) {
22565                if (opti >= args.length) {
22566                    pw.println("Error: permission requires permission name");
22567                    return;
22568                }
22569                permissionNames = new ArraySet<>();
22570                while (opti < args.length) {
22571                    permissionNames.add(args[opti]);
22572                    opti++;
22573                }
22574                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22575                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22576            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22577                dumpState.setDump(DumpState.DUMP_PREFERRED);
22578            } else if ("preferred-xml".equals(cmd)) {
22579                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22580                if (opti < args.length && "--full".equals(args[opti])) {
22581                    fullPreferred = true;
22582                    opti++;
22583                }
22584            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22585                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22586            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22587                dumpState.setDump(DumpState.DUMP_PACKAGES);
22588            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22589                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22590            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22591                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22592            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22593                dumpState.setDump(DumpState.DUMP_MESSAGES);
22594            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22595                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22596            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22597                    || "intent-filter-verifiers".equals(cmd)) {
22598                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22599            } else if ("version".equals(cmd)) {
22600                dumpState.setDump(DumpState.DUMP_VERSION);
22601            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22602                dumpState.setDump(DumpState.DUMP_KEYSETS);
22603            } else if ("installs".equals(cmd)) {
22604                dumpState.setDump(DumpState.DUMP_INSTALLS);
22605            } else if ("frozen".equals(cmd)) {
22606                dumpState.setDump(DumpState.DUMP_FROZEN);
22607            } else if ("volumes".equals(cmd)) {
22608                dumpState.setDump(DumpState.DUMP_VOLUMES);
22609            } else if ("dexopt".equals(cmd)) {
22610                dumpState.setDump(DumpState.DUMP_DEXOPT);
22611            } else if ("compiler-stats".equals(cmd)) {
22612                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22613            } else if ("changes".equals(cmd)) {
22614                dumpState.setDump(DumpState.DUMP_CHANGES);
22615            } else if ("write".equals(cmd)) {
22616                synchronized (mPackages) {
22617                    mSettings.writeLPr();
22618                    pw.println("Settings written.");
22619                    return;
22620                }
22621            }
22622        }
22623
22624        if (checkin) {
22625            pw.println("vers,1");
22626        }
22627
22628        // reader
22629        synchronized (mPackages) {
22630            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22631                if (!checkin) {
22632                    if (dumpState.onTitlePrinted())
22633                        pw.println();
22634                    pw.println("Database versions:");
22635                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22636                }
22637            }
22638
22639            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22640                if (!checkin) {
22641                    if (dumpState.onTitlePrinted())
22642                        pw.println();
22643                    pw.println("Verifiers:");
22644                    pw.print("  Required: ");
22645                    pw.print(mRequiredVerifierPackage);
22646                    pw.print(" (uid=");
22647                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22648                            UserHandle.USER_SYSTEM));
22649                    pw.println(")");
22650                } else if (mRequiredVerifierPackage != null) {
22651                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22652                    pw.print(",");
22653                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22654                            UserHandle.USER_SYSTEM));
22655                }
22656            }
22657
22658            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22659                    packageName == null) {
22660                if (mIntentFilterVerifierComponent != null) {
22661                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22662                    if (!checkin) {
22663                        if (dumpState.onTitlePrinted())
22664                            pw.println();
22665                        pw.println("Intent Filter Verifier:");
22666                        pw.print("  Using: ");
22667                        pw.print(verifierPackageName);
22668                        pw.print(" (uid=");
22669                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22670                                UserHandle.USER_SYSTEM));
22671                        pw.println(")");
22672                    } else if (verifierPackageName != null) {
22673                        pw.print("ifv,"); pw.print(verifierPackageName);
22674                        pw.print(",");
22675                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22676                                UserHandle.USER_SYSTEM));
22677                    }
22678                } else {
22679                    pw.println();
22680                    pw.println("No Intent Filter Verifier available!");
22681                }
22682            }
22683
22684            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22685                boolean printedHeader = false;
22686                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22687                while (it.hasNext()) {
22688                    String libName = it.next();
22689                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22690                    if (versionedLib == null) {
22691                        continue;
22692                    }
22693                    final int versionCount = versionedLib.size();
22694                    for (int i = 0; i < versionCount; i++) {
22695                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22696                        if (!checkin) {
22697                            if (!printedHeader) {
22698                                if (dumpState.onTitlePrinted())
22699                                    pw.println();
22700                                pw.println("Libraries:");
22701                                printedHeader = true;
22702                            }
22703                            pw.print("  ");
22704                        } else {
22705                            pw.print("lib,");
22706                        }
22707                        pw.print(libEntry.info.getName());
22708                        if (libEntry.info.isStatic()) {
22709                            pw.print(" version=" + libEntry.info.getVersion());
22710                        }
22711                        if (!checkin) {
22712                            pw.print(" -> ");
22713                        }
22714                        if (libEntry.path != null) {
22715                            pw.print(" (jar) ");
22716                            pw.print(libEntry.path);
22717                        } else {
22718                            pw.print(" (apk) ");
22719                            pw.print(libEntry.apk);
22720                        }
22721                        pw.println();
22722                    }
22723                }
22724            }
22725
22726            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22727                if (dumpState.onTitlePrinted())
22728                    pw.println();
22729                if (!checkin) {
22730                    pw.println("Features:");
22731                }
22732
22733                synchronized (mAvailableFeatures) {
22734                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22735                        if (checkin) {
22736                            pw.print("feat,");
22737                            pw.print(feat.name);
22738                            pw.print(",");
22739                            pw.println(feat.version);
22740                        } else {
22741                            pw.print("  ");
22742                            pw.print(feat.name);
22743                            if (feat.version > 0) {
22744                                pw.print(" version=");
22745                                pw.print(feat.version);
22746                            }
22747                            pw.println();
22748                        }
22749                    }
22750                }
22751            }
22752
22753            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22754                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22755                        : "Activity Resolver Table:", "  ", packageName,
22756                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22757                    dumpState.setTitlePrinted(true);
22758                }
22759            }
22760            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22761                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22762                        : "Receiver Resolver Table:", "  ", packageName,
22763                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22764                    dumpState.setTitlePrinted(true);
22765                }
22766            }
22767            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22768                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22769                        : "Service Resolver Table:", "  ", packageName,
22770                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22771                    dumpState.setTitlePrinted(true);
22772                }
22773            }
22774            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22775                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22776                        : "Provider Resolver Table:", "  ", packageName,
22777                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22778                    dumpState.setTitlePrinted(true);
22779                }
22780            }
22781
22782            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22783                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22784                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22785                    int user = mSettings.mPreferredActivities.keyAt(i);
22786                    if (pir.dump(pw,
22787                            dumpState.getTitlePrinted()
22788                                ? "\nPreferred Activities User " + user + ":"
22789                                : "Preferred Activities User " + user + ":", "  ",
22790                            packageName, true, false)) {
22791                        dumpState.setTitlePrinted(true);
22792                    }
22793                }
22794            }
22795
22796            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22797                pw.flush();
22798                FileOutputStream fout = new FileOutputStream(fd);
22799                BufferedOutputStream str = new BufferedOutputStream(fout);
22800                XmlSerializer serializer = new FastXmlSerializer();
22801                try {
22802                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22803                    serializer.startDocument(null, true);
22804                    serializer.setFeature(
22805                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22806                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22807                    serializer.endDocument();
22808                    serializer.flush();
22809                } catch (IllegalArgumentException e) {
22810                    pw.println("Failed writing: " + e);
22811                } catch (IllegalStateException e) {
22812                    pw.println("Failed writing: " + e);
22813                } catch (IOException e) {
22814                    pw.println("Failed writing: " + e);
22815                }
22816            }
22817
22818            if (!checkin
22819                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22820                    && packageName == null) {
22821                pw.println();
22822                int count = mSettings.mPackages.size();
22823                if (count == 0) {
22824                    pw.println("No applications!");
22825                    pw.println();
22826                } else {
22827                    final String prefix = "  ";
22828                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22829                    if (allPackageSettings.size() == 0) {
22830                        pw.println("No domain preferred apps!");
22831                        pw.println();
22832                    } else {
22833                        pw.println("App verification status:");
22834                        pw.println();
22835                        count = 0;
22836                        for (PackageSetting ps : allPackageSettings) {
22837                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22838                            if (ivi == null || ivi.getPackageName() == null) continue;
22839                            pw.println(prefix + "Package: " + ivi.getPackageName());
22840                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22841                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22842                            pw.println();
22843                            count++;
22844                        }
22845                        if (count == 0) {
22846                            pw.println(prefix + "No app verification established.");
22847                            pw.println();
22848                        }
22849                        for (int userId : sUserManager.getUserIds()) {
22850                            pw.println("App linkages for user " + userId + ":");
22851                            pw.println();
22852                            count = 0;
22853                            for (PackageSetting ps : allPackageSettings) {
22854                                final long status = ps.getDomainVerificationStatusForUser(userId);
22855                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22856                                        && !DEBUG_DOMAIN_VERIFICATION) {
22857                                    continue;
22858                                }
22859                                pw.println(prefix + "Package: " + ps.name);
22860                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22861                                String statusStr = IntentFilterVerificationInfo.
22862                                        getStatusStringFromValue(status);
22863                                pw.println(prefix + "Status:  " + statusStr);
22864                                pw.println();
22865                                count++;
22866                            }
22867                            if (count == 0) {
22868                                pw.println(prefix + "No configured app linkages.");
22869                                pw.println();
22870                            }
22871                        }
22872                    }
22873                }
22874            }
22875
22876            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22877                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22878                if (packageName == null && permissionNames == null) {
22879                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22880                        if (iperm == 0) {
22881                            if (dumpState.onTitlePrinted())
22882                                pw.println();
22883                            pw.println("AppOp Permissions:");
22884                        }
22885                        pw.print("  AppOp Permission ");
22886                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22887                        pw.println(":");
22888                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22889                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22890                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22891                        }
22892                    }
22893                }
22894            }
22895
22896            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22897                boolean printedSomething = false;
22898                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22899                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22900                        continue;
22901                    }
22902                    if (!printedSomething) {
22903                        if (dumpState.onTitlePrinted())
22904                            pw.println();
22905                        pw.println("Registered ContentProviders:");
22906                        printedSomething = true;
22907                    }
22908                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22909                    pw.print("    "); pw.println(p.toString());
22910                }
22911                printedSomething = false;
22912                for (Map.Entry<String, PackageParser.Provider> entry :
22913                        mProvidersByAuthority.entrySet()) {
22914                    PackageParser.Provider p = entry.getValue();
22915                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22916                        continue;
22917                    }
22918                    if (!printedSomething) {
22919                        if (dumpState.onTitlePrinted())
22920                            pw.println();
22921                        pw.println("ContentProvider Authorities:");
22922                        printedSomething = true;
22923                    }
22924                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22925                    pw.print("    "); pw.println(p.toString());
22926                    if (p.info != null && p.info.applicationInfo != null) {
22927                        final String appInfo = p.info.applicationInfo.toString();
22928                        pw.print("      applicationInfo="); pw.println(appInfo);
22929                    }
22930                }
22931            }
22932
22933            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22934                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22935            }
22936
22937            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22938                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22939            }
22940
22941            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22942                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22943            }
22944
22945            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22946                if (dumpState.onTitlePrinted()) pw.println();
22947                pw.println("Package Changes:");
22948                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22949                final int K = mChangedPackages.size();
22950                for (int i = 0; i < K; i++) {
22951                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22952                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22953                    final int N = changes.size();
22954                    if (N == 0) {
22955                        pw.print("    "); pw.println("No packages changed");
22956                    } else {
22957                        for (int j = 0; j < N; j++) {
22958                            final String pkgName = changes.valueAt(j);
22959                            final int sequenceNumber = changes.keyAt(j);
22960                            pw.print("    ");
22961                            pw.print("seq=");
22962                            pw.print(sequenceNumber);
22963                            pw.print(", package=");
22964                            pw.println(pkgName);
22965                        }
22966                    }
22967                }
22968            }
22969
22970            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22971                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22972            }
22973
22974            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22975                // XXX should handle packageName != null by dumping only install data that
22976                // the given package is involved with.
22977                if (dumpState.onTitlePrinted()) pw.println();
22978
22979                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22980                ipw.println();
22981                ipw.println("Frozen packages:");
22982                ipw.increaseIndent();
22983                if (mFrozenPackages.size() == 0) {
22984                    ipw.println("(none)");
22985                } else {
22986                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22987                        ipw.println(mFrozenPackages.valueAt(i));
22988                    }
22989                }
22990                ipw.decreaseIndent();
22991            }
22992
22993            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22994                if (dumpState.onTitlePrinted()) pw.println();
22995
22996                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22997                ipw.println();
22998                ipw.println("Loaded volumes:");
22999                ipw.increaseIndent();
23000                if (mLoadedVolumes.size() == 0) {
23001                    ipw.println("(none)");
23002                } else {
23003                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
23004                        ipw.println(mLoadedVolumes.valueAt(i));
23005                    }
23006                }
23007                ipw.decreaseIndent();
23008            }
23009
23010            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
23011                if (dumpState.onTitlePrinted()) pw.println();
23012                dumpDexoptStateLPr(pw, packageName);
23013            }
23014
23015            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
23016                if (dumpState.onTitlePrinted()) pw.println();
23017                dumpCompilerStatsLPr(pw, packageName);
23018            }
23019
23020            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
23021                if (dumpState.onTitlePrinted()) pw.println();
23022                mSettings.dumpReadMessagesLPr(pw, dumpState);
23023
23024                pw.println();
23025                pw.println("Package warning messages:");
23026                BufferedReader in = null;
23027                String line = null;
23028                try {
23029                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23030                    while ((line = in.readLine()) != null) {
23031                        if (line.contains("ignored: updated version")) continue;
23032                        pw.println(line);
23033                    }
23034                } catch (IOException ignored) {
23035                } finally {
23036                    IoUtils.closeQuietly(in);
23037                }
23038            }
23039
23040            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
23041                BufferedReader in = null;
23042                String line = null;
23043                try {
23044                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23045                    while ((line = in.readLine()) != null) {
23046                        if (line.contains("ignored: updated version")) continue;
23047                        pw.print("msg,");
23048                        pw.println(line);
23049                    }
23050                } catch (IOException ignored) {
23051                } finally {
23052                    IoUtils.closeQuietly(in);
23053                }
23054            }
23055        }
23056
23057        // PackageInstaller should be called outside of mPackages lock
23058        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
23059            // XXX should handle packageName != null by dumping only install data that
23060            // the given package is involved with.
23061            if (dumpState.onTitlePrinted()) pw.println();
23062            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
23063        }
23064    }
23065
23066    private void dumpProto(FileDescriptor fd) {
23067        final ProtoOutputStream proto = new ProtoOutputStream(fd);
23068
23069        synchronized (mPackages) {
23070            final long requiredVerifierPackageToken =
23071                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
23072            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
23073            proto.write(
23074                    PackageServiceDumpProto.PackageShortProto.UID,
23075                    getPackageUid(
23076                            mRequiredVerifierPackage,
23077                            MATCH_DEBUG_TRIAGED_MISSING,
23078                            UserHandle.USER_SYSTEM));
23079            proto.end(requiredVerifierPackageToken);
23080
23081            if (mIntentFilterVerifierComponent != null) {
23082                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
23083                final long verifierPackageToken =
23084                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
23085                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
23086                proto.write(
23087                        PackageServiceDumpProto.PackageShortProto.UID,
23088                        getPackageUid(
23089                                verifierPackageName,
23090                                MATCH_DEBUG_TRIAGED_MISSING,
23091                                UserHandle.USER_SYSTEM));
23092                proto.end(verifierPackageToken);
23093            }
23094
23095            dumpSharedLibrariesProto(proto);
23096            dumpFeaturesProto(proto);
23097            mSettings.dumpPackagesProto(proto);
23098            mSettings.dumpSharedUsersProto(proto);
23099            dumpMessagesProto(proto);
23100        }
23101        proto.flush();
23102    }
23103
23104    private void dumpMessagesProto(ProtoOutputStream proto) {
23105        BufferedReader in = null;
23106        String line = null;
23107        try {
23108            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23109            while ((line = in.readLine()) != null) {
23110                if (line.contains("ignored: updated version")) continue;
23111                proto.write(PackageServiceDumpProto.MESSAGES, line);
23112            }
23113        } catch (IOException ignored) {
23114        } finally {
23115            IoUtils.closeQuietly(in);
23116        }
23117    }
23118
23119    private void dumpFeaturesProto(ProtoOutputStream proto) {
23120        synchronized (mAvailableFeatures) {
23121            final int count = mAvailableFeatures.size();
23122            for (int i = 0; i < count; i++) {
23123                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
23124                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
23125                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
23126                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
23127                proto.end(featureToken);
23128            }
23129        }
23130    }
23131
23132    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
23133        final int count = mSharedLibraries.size();
23134        for (int i = 0; i < count; i++) {
23135            final String libName = mSharedLibraries.keyAt(i);
23136            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
23137            if (versionedLib == null) {
23138                continue;
23139            }
23140            final int versionCount = versionedLib.size();
23141            for (int j = 0; j < versionCount; j++) {
23142                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23143                final long sharedLibraryToken =
23144                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23145                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23146                final boolean isJar = (libEntry.path != null);
23147                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23148                if (isJar) {
23149                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23150                } else {
23151                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23152                }
23153                proto.end(sharedLibraryToken);
23154            }
23155        }
23156    }
23157
23158    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23159        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23160        ipw.println();
23161        ipw.println("Dexopt state:");
23162        ipw.increaseIndent();
23163        Collection<PackageParser.Package> packages = null;
23164        if (packageName != null) {
23165            PackageParser.Package targetPackage = mPackages.get(packageName);
23166            if (targetPackage != null) {
23167                packages = Collections.singletonList(targetPackage);
23168            } else {
23169                ipw.println("Unable to find package: " + packageName);
23170                return;
23171            }
23172        } else {
23173            packages = mPackages.values();
23174        }
23175
23176        for (PackageParser.Package pkg : packages) {
23177            ipw.println("[" + pkg.packageName + "]");
23178            ipw.increaseIndent();
23179            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23180                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23181            ipw.decreaseIndent();
23182        }
23183    }
23184
23185    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23186        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23187        ipw.println();
23188        ipw.println("Compiler stats:");
23189        ipw.increaseIndent();
23190        Collection<PackageParser.Package> packages = null;
23191        if (packageName != null) {
23192            PackageParser.Package targetPackage = mPackages.get(packageName);
23193            if (targetPackage != null) {
23194                packages = Collections.singletonList(targetPackage);
23195            } else {
23196                ipw.println("Unable to find package: " + packageName);
23197                return;
23198            }
23199        } else {
23200            packages = mPackages.values();
23201        }
23202
23203        for (PackageParser.Package pkg : packages) {
23204            ipw.println("[" + pkg.packageName + "]");
23205            ipw.increaseIndent();
23206
23207            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23208            if (stats == null) {
23209                ipw.println("(No recorded stats)");
23210            } else {
23211                stats.dump(ipw);
23212            }
23213            ipw.decreaseIndent();
23214        }
23215    }
23216
23217    private String dumpDomainString(String packageName) {
23218        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23219                .getList();
23220        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23221
23222        ArraySet<String> result = new ArraySet<>();
23223        if (iviList.size() > 0) {
23224            for (IntentFilterVerificationInfo ivi : iviList) {
23225                for (String host : ivi.getDomains()) {
23226                    result.add(host);
23227                }
23228            }
23229        }
23230        if (filters != null && filters.size() > 0) {
23231            for (IntentFilter filter : filters) {
23232                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23233                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23234                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23235                    result.addAll(filter.getHostsList());
23236                }
23237            }
23238        }
23239
23240        StringBuilder sb = new StringBuilder(result.size() * 16);
23241        for (String domain : result) {
23242            if (sb.length() > 0) sb.append(" ");
23243            sb.append(domain);
23244        }
23245        return sb.toString();
23246    }
23247
23248    // ------- apps on sdcard specific code -------
23249    static final boolean DEBUG_SD_INSTALL = false;
23250
23251    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23252
23253    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23254
23255    private boolean mMediaMounted = false;
23256
23257    static String getEncryptKey() {
23258        try {
23259            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23260                    SD_ENCRYPTION_KEYSTORE_NAME);
23261            if (sdEncKey == null) {
23262                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23263                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23264                if (sdEncKey == null) {
23265                    Slog.e(TAG, "Failed to create encryption keys");
23266                    return null;
23267                }
23268            }
23269            return sdEncKey;
23270        } catch (NoSuchAlgorithmException nsae) {
23271            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23272            return null;
23273        } catch (IOException ioe) {
23274            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23275            return null;
23276        }
23277    }
23278
23279    /*
23280     * Update media status on PackageManager.
23281     */
23282    @Override
23283    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23284        enforceSystemOrRoot("Media status can only be updated by the system");
23285        // reader; this apparently protects mMediaMounted, but should probably
23286        // be a different lock in that case.
23287        synchronized (mPackages) {
23288            Log.i(TAG, "Updating external media status from "
23289                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23290                    + (mediaStatus ? "mounted" : "unmounted"));
23291            if (DEBUG_SD_INSTALL)
23292                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23293                        + ", mMediaMounted=" + mMediaMounted);
23294            if (mediaStatus == mMediaMounted) {
23295                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23296                        : 0, -1);
23297                mHandler.sendMessage(msg);
23298                return;
23299            }
23300            mMediaMounted = mediaStatus;
23301        }
23302        // Queue up an async operation since the package installation may take a
23303        // little while.
23304        mHandler.post(new Runnable() {
23305            public void run() {
23306                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23307            }
23308        });
23309    }
23310
23311    /**
23312     * Called by StorageManagerService when the initial ASECs to scan are available.
23313     * Should block until all the ASEC containers are finished being scanned.
23314     */
23315    public void scanAvailableAsecs() {
23316        updateExternalMediaStatusInner(true, false, false);
23317    }
23318
23319    /*
23320     * Collect information of applications on external media, map them against
23321     * existing containers and update information based on current mount status.
23322     * Please note that we always have to report status if reportStatus has been
23323     * set to true especially when unloading packages.
23324     */
23325    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23326            boolean externalStorage) {
23327        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23328        int[] uidArr = EmptyArray.INT;
23329
23330        final String[] list = PackageHelper.getSecureContainerList();
23331        if (ArrayUtils.isEmpty(list)) {
23332            Log.i(TAG, "No secure containers found");
23333        } else {
23334            // Process list of secure containers and categorize them
23335            // as active or stale based on their package internal state.
23336
23337            // reader
23338            synchronized (mPackages) {
23339                for (String cid : list) {
23340                    // Leave stages untouched for now; installer service owns them
23341                    if (PackageInstallerService.isStageName(cid)) continue;
23342
23343                    if (DEBUG_SD_INSTALL)
23344                        Log.i(TAG, "Processing container " + cid);
23345                    String pkgName = getAsecPackageName(cid);
23346                    if (pkgName == null) {
23347                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23348                        continue;
23349                    }
23350                    if (DEBUG_SD_INSTALL)
23351                        Log.i(TAG, "Looking for pkg : " + pkgName);
23352
23353                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23354                    if (ps == null) {
23355                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23356                        continue;
23357                    }
23358
23359                    /*
23360                     * Skip packages that are not external if we're unmounting
23361                     * external storage.
23362                     */
23363                    if (externalStorage && !isMounted && !isExternal(ps)) {
23364                        continue;
23365                    }
23366
23367                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23368                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23369                    // The package status is changed only if the code path
23370                    // matches between settings and the container id.
23371                    if (ps.codePathString != null
23372                            && ps.codePathString.startsWith(args.getCodePath())) {
23373                        if (DEBUG_SD_INSTALL) {
23374                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23375                                    + " at code path: " + ps.codePathString);
23376                        }
23377
23378                        // We do have a valid package installed on sdcard
23379                        processCids.put(args, ps.codePathString);
23380                        final int uid = ps.appId;
23381                        if (uid != -1) {
23382                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23383                        }
23384                    } else {
23385                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23386                                + ps.codePathString);
23387                    }
23388                }
23389            }
23390
23391            Arrays.sort(uidArr);
23392        }
23393
23394        // Process packages with valid entries.
23395        if (isMounted) {
23396            if (DEBUG_SD_INSTALL)
23397                Log.i(TAG, "Loading packages");
23398            loadMediaPackages(processCids, uidArr, externalStorage);
23399            startCleaningPackages();
23400            mInstallerService.onSecureContainersAvailable();
23401        } else {
23402            if (DEBUG_SD_INSTALL)
23403                Log.i(TAG, "Unloading packages");
23404            unloadMediaPackages(processCids, uidArr, reportStatus);
23405        }
23406    }
23407
23408    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23409            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23410        final int size = infos.size();
23411        final String[] packageNames = new String[size];
23412        final int[] packageUids = new int[size];
23413        for (int i = 0; i < size; i++) {
23414            final ApplicationInfo info = infos.get(i);
23415            packageNames[i] = info.packageName;
23416            packageUids[i] = info.uid;
23417        }
23418        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23419                finishedReceiver);
23420    }
23421
23422    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23423            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23424        sendResourcesChangedBroadcast(mediaStatus, replacing,
23425                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23426    }
23427
23428    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23429            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23430        int size = pkgList.length;
23431        if (size > 0) {
23432            // Send broadcasts here
23433            Bundle extras = new Bundle();
23434            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23435            if (uidArr != null) {
23436                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23437            }
23438            if (replacing) {
23439                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23440            }
23441            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23442                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23443            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23444        }
23445    }
23446
23447   /*
23448     * Look at potentially valid container ids from processCids If package
23449     * information doesn't match the one on record or package scanning fails,
23450     * the cid is added to list of removeCids. We currently don't delete stale
23451     * containers.
23452     */
23453    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23454            boolean externalStorage) {
23455        ArrayList<String> pkgList = new ArrayList<String>();
23456        Set<AsecInstallArgs> keys = processCids.keySet();
23457
23458        for (AsecInstallArgs args : keys) {
23459            String codePath = processCids.get(args);
23460            if (DEBUG_SD_INSTALL)
23461                Log.i(TAG, "Loading container : " + args.cid);
23462            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23463            try {
23464                // Make sure there are no container errors first.
23465                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23466                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23467                            + " when installing from sdcard");
23468                    continue;
23469                }
23470                // Check code path here.
23471                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23472                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23473                            + " does not match one in settings " + codePath);
23474                    continue;
23475                }
23476                // Parse package
23477                int parseFlags = mDefParseFlags;
23478                if (args.isExternalAsec()) {
23479                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23480                }
23481                if (args.isFwdLocked()) {
23482                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23483                }
23484
23485                synchronized (mInstallLock) {
23486                    PackageParser.Package pkg = null;
23487                    try {
23488                        // Sadly we don't know the package name yet to freeze it
23489                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23490                                SCAN_IGNORE_FROZEN, 0, null);
23491                    } catch (PackageManagerException e) {
23492                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23493                    }
23494                    // Scan the package
23495                    if (pkg != null) {
23496                        /*
23497                         * TODO why is the lock being held? doPostInstall is
23498                         * called in other places without the lock. This needs
23499                         * to be straightened out.
23500                         */
23501                        // writer
23502                        synchronized (mPackages) {
23503                            retCode = PackageManager.INSTALL_SUCCEEDED;
23504                            pkgList.add(pkg.packageName);
23505                            // Post process args
23506                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23507                                    pkg.applicationInfo.uid);
23508                        }
23509                    } else {
23510                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23511                    }
23512                }
23513
23514            } finally {
23515                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23516                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23517                }
23518            }
23519        }
23520        // writer
23521        synchronized (mPackages) {
23522            // If the platform SDK has changed since the last time we booted,
23523            // we need to re-grant app permission to catch any new ones that
23524            // appear. This is really a hack, and means that apps can in some
23525            // cases get permissions that the user didn't initially explicitly
23526            // allow... it would be nice to have some better way to handle
23527            // this situation.
23528            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23529                    : mSettings.getInternalVersion();
23530            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23531                    : StorageManager.UUID_PRIVATE_INTERNAL;
23532
23533            int updateFlags = UPDATE_PERMISSIONS_ALL;
23534            if (ver.sdkVersion != mSdkVersion) {
23535                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23536                        + mSdkVersion + "; regranting permissions for external");
23537                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23538            }
23539            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23540
23541            // Yay, everything is now upgraded
23542            ver.forceCurrent();
23543
23544            // can downgrade to reader
23545            // Persist settings
23546            mSettings.writeLPr();
23547        }
23548        // Send a broadcast to let everyone know we are done processing
23549        if (pkgList.size() > 0) {
23550            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23551        }
23552    }
23553
23554   /*
23555     * Utility method to unload a list of specified containers
23556     */
23557    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23558        // Just unmount all valid containers.
23559        for (AsecInstallArgs arg : cidArgs) {
23560            synchronized (mInstallLock) {
23561                arg.doPostDeleteLI(false);
23562           }
23563       }
23564   }
23565
23566    /*
23567     * Unload packages mounted on external media. This involves deleting package
23568     * data from internal structures, sending broadcasts about disabled packages,
23569     * gc'ing to free up references, unmounting all secure containers
23570     * corresponding to packages on external media, and posting a
23571     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23572     * that we always have to post this message if status has been requested no
23573     * matter what.
23574     */
23575    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23576            final boolean reportStatus) {
23577        if (DEBUG_SD_INSTALL)
23578            Log.i(TAG, "unloading media packages");
23579        ArrayList<String> pkgList = new ArrayList<String>();
23580        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23581        final Set<AsecInstallArgs> keys = processCids.keySet();
23582        for (AsecInstallArgs args : keys) {
23583            String pkgName = args.getPackageName();
23584            if (DEBUG_SD_INSTALL)
23585                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23586            // Delete package internally
23587            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23588            synchronized (mInstallLock) {
23589                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23590                final boolean res;
23591                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23592                        "unloadMediaPackages")) {
23593                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23594                            null);
23595                }
23596                if (res) {
23597                    pkgList.add(pkgName);
23598                } else {
23599                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23600                    failedList.add(args);
23601                }
23602            }
23603        }
23604
23605        // reader
23606        synchronized (mPackages) {
23607            // We didn't update the settings after removing each package;
23608            // write them now for all packages.
23609            mSettings.writeLPr();
23610        }
23611
23612        // We have to absolutely send UPDATED_MEDIA_STATUS only
23613        // after confirming that all the receivers processed the ordered
23614        // broadcast when packages get disabled, force a gc to clean things up.
23615        // and unload all the containers.
23616        if (pkgList.size() > 0) {
23617            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23618                    new IIntentReceiver.Stub() {
23619                public void performReceive(Intent intent, int resultCode, String data,
23620                        Bundle extras, boolean ordered, boolean sticky,
23621                        int sendingUser) throws RemoteException {
23622                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23623                            reportStatus ? 1 : 0, 1, keys);
23624                    mHandler.sendMessage(msg);
23625                }
23626            });
23627        } else {
23628            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23629                    keys);
23630            mHandler.sendMessage(msg);
23631        }
23632    }
23633
23634    private void loadPrivatePackages(final VolumeInfo vol) {
23635        mHandler.post(new Runnable() {
23636            @Override
23637            public void run() {
23638                loadPrivatePackagesInner(vol);
23639            }
23640        });
23641    }
23642
23643    private void loadPrivatePackagesInner(VolumeInfo vol) {
23644        final String volumeUuid = vol.fsUuid;
23645        if (TextUtils.isEmpty(volumeUuid)) {
23646            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23647            return;
23648        }
23649
23650        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23651        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23652        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23653
23654        final VersionInfo ver;
23655        final List<PackageSetting> packages;
23656        synchronized (mPackages) {
23657            ver = mSettings.findOrCreateVersion(volumeUuid);
23658            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23659        }
23660
23661        for (PackageSetting ps : packages) {
23662            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23663            synchronized (mInstallLock) {
23664                final PackageParser.Package pkg;
23665                try {
23666                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23667                    loaded.add(pkg.applicationInfo);
23668
23669                } catch (PackageManagerException e) {
23670                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23671                }
23672
23673                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23674                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23675                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23676                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23677                }
23678            }
23679        }
23680
23681        // Reconcile app data for all started/unlocked users
23682        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23683        final UserManager um = mContext.getSystemService(UserManager.class);
23684        UserManagerInternal umInternal = getUserManagerInternal();
23685        for (UserInfo user : um.getUsers()) {
23686            final int flags;
23687            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23688                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23689            } else if (umInternal.isUserRunning(user.id)) {
23690                flags = StorageManager.FLAG_STORAGE_DE;
23691            } else {
23692                continue;
23693            }
23694
23695            try {
23696                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23697                synchronized (mInstallLock) {
23698                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23699                }
23700            } catch (IllegalStateException e) {
23701                // Device was probably ejected, and we'll process that event momentarily
23702                Slog.w(TAG, "Failed to prepare storage: " + e);
23703            }
23704        }
23705
23706        synchronized (mPackages) {
23707            int updateFlags = UPDATE_PERMISSIONS_ALL;
23708            if (ver.sdkVersion != mSdkVersion) {
23709                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23710                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23711                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23712            }
23713            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23714
23715            // Yay, everything is now upgraded
23716            ver.forceCurrent();
23717
23718            mSettings.writeLPr();
23719        }
23720
23721        for (PackageFreezer freezer : freezers) {
23722            freezer.close();
23723        }
23724
23725        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23726        sendResourcesChangedBroadcast(true, false, loaded, null);
23727        mLoadedVolumes.add(vol.getId());
23728    }
23729
23730    private void unloadPrivatePackages(final VolumeInfo vol) {
23731        mHandler.post(new Runnable() {
23732            @Override
23733            public void run() {
23734                unloadPrivatePackagesInner(vol);
23735            }
23736        });
23737    }
23738
23739    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23740        final String volumeUuid = vol.fsUuid;
23741        if (TextUtils.isEmpty(volumeUuid)) {
23742            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23743            return;
23744        }
23745
23746        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23747        synchronized (mInstallLock) {
23748        synchronized (mPackages) {
23749            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23750            for (PackageSetting ps : packages) {
23751                if (ps.pkg == null) continue;
23752
23753                final ApplicationInfo info = ps.pkg.applicationInfo;
23754                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23755                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23756
23757                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23758                        "unloadPrivatePackagesInner")) {
23759                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23760                            false, null)) {
23761                        unloaded.add(info);
23762                    } else {
23763                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23764                    }
23765                }
23766
23767                // Try very hard to release any references to this package
23768                // so we don't risk the system server being killed due to
23769                // open FDs
23770                AttributeCache.instance().removePackage(ps.name);
23771            }
23772
23773            mSettings.writeLPr();
23774        }
23775        }
23776
23777        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23778        sendResourcesChangedBroadcast(false, false, unloaded, null);
23779        mLoadedVolumes.remove(vol.getId());
23780
23781        // Try very hard to release any references to this path so we don't risk
23782        // the system server being killed due to open FDs
23783        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23784
23785        for (int i = 0; i < 3; i++) {
23786            System.gc();
23787            System.runFinalization();
23788        }
23789    }
23790
23791    private void assertPackageKnown(String volumeUuid, String packageName)
23792            throws PackageManagerException {
23793        synchronized (mPackages) {
23794            // Normalize package name to handle renamed packages
23795            packageName = normalizePackageNameLPr(packageName);
23796
23797            final PackageSetting ps = mSettings.mPackages.get(packageName);
23798            if (ps == null) {
23799                throw new PackageManagerException("Package " + packageName + " is unknown");
23800            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23801                throw new PackageManagerException(
23802                        "Package " + packageName + " found on unknown volume " + volumeUuid
23803                                + "; expected volume " + ps.volumeUuid);
23804            }
23805        }
23806    }
23807
23808    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23809            throws PackageManagerException {
23810        synchronized (mPackages) {
23811            // Normalize package name to handle renamed packages
23812            packageName = normalizePackageNameLPr(packageName);
23813
23814            final PackageSetting ps = mSettings.mPackages.get(packageName);
23815            if (ps == null) {
23816                throw new PackageManagerException("Package " + packageName + " is unknown");
23817            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23818                throw new PackageManagerException(
23819                        "Package " + packageName + " found on unknown volume " + volumeUuid
23820                                + "; expected volume " + ps.volumeUuid);
23821            } else if (!ps.getInstalled(userId)) {
23822                throw new PackageManagerException(
23823                        "Package " + packageName + " not installed for user " + userId);
23824            }
23825        }
23826    }
23827
23828    private List<String> collectAbsoluteCodePaths() {
23829        synchronized (mPackages) {
23830            List<String> codePaths = new ArrayList<>();
23831            final int packageCount = mSettings.mPackages.size();
23832            for (int i = 0; i < packageCount; i++) {
23833                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23834                codePaths.add(ps.codePath.getAbsolutePath());
23835            }
23836            return codePaths;
23837        }
23838    }
23839
23840    /**
23841     * Examine all apps present on given mounted volume, and destroy apps that
23842     * aren't expected, either due to uninstallation or reinstallation on
23843     * another volume.
23844     */
23845    private void reconcileApps(String volumeUuid) {
23846        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23847        List<File> filesToDelete = null;
23848
23849        final File[] files = FileUtils.listFilesOrEmpty(
23850                Environment.getDataAppDirectory(volumeUuid));
23851        for (File file : files) {
23852            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23853                    && !PackageInstallerService.isStageName(file.getName());
23854            if (!isPackage) {
23855                // Ignore entries which are not packages
23856                continue;
23857            }
23858
23859            String absolutePath = file.getAbsolutePath();
23860
23861            boolean pathValid = false;
23862            final int absoluteCodePathCount = absoluteCodePaths.size();
23863            for (int i = 0; i < absoluteCodePathCount; i++) {
23864                String absoluteCodePath = absoluteCodePaths.get(i);
23865                if (absolutePath.startsWith(absoluteCodePath)) {
23866                    pathValid = true;
23867                    break;
23868                }
23869            }
23870
23871            if (!pathValid) {
23872                if (filesToDelete == null) {
23873                    filesToDelete = new ArrayList<>();
23874                }
23875                filesToDelete.add(file);
23876            }
23877        }
23878
23879        if (filesToDelete != null) {
23880            final int fileToDeleteCount = filesToDelete.size();
23881            for (int i = 0; i < fileToDeleteCount; i++) {
23882                File fileToDelete = filesToDelete.get(i);
23883                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23884                synchronized (mInstallLock) {
23885                    removeCodePathLI(fileToDelete);
23886                }
23887            }
23888        }
23889    }
23890
23891    /**
23892     * Reconcile all app data for the given user.
23893     * <p>
23894     * Verifies that directories exist and that ownership and labeling is
23895     * correct for all installed apps on all mounted volumes.
23896     */
23897    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23898        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23899        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23900            final String volumeUuid = vol.getFsUuid();
23901            synchronized (mInstallLock) {
23902                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23903            }
23904        }
23905    }
23906
23907    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23908            boolean migrateAppData) {
23909        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23910    }
23911
23912    /**
23913     * Reconcile all app data on given mounted volume.
23914     * <p>
23915     * Destroys app data that isn't expected, either due to uninstallation or
23916     * reinstallation on another volume.
23917     * <p>
23918     * Verifies that directories exist and that ownership and labeling is
23919     * correct for all installed apps.
23920     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23921     */
23922    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23923            boolean migrateAppData, boolean onlyCoreApps) {
23924        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23925                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23926        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23927
23928        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23929        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23930
23931        // First look for stale data that doesn't belong, and check if things
23932        // have changed since we did our last restorecon
23933        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23934            if (StorageManager.isFileEncryptedNativeOrEmulated()
23935                    && !StorageManager.isUserKeyUnlocked(userId)) {
23936                throw new RuntimeException(
23937                        "Yikes, someone asked us to reconcile CE storage while " + userId
23938                                + " was still locked; this would have caused massive data loss!");
23939            }
23940
23941            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23942            for (File file : files) {
23943                final String packageName = file.getName();
23944                try {
23945                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23946                } catch (PackageManagerException e) {
23947                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23948                    try {
23949                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23950                                StorageManager.FLAG_STORAGE_CE, 0);
23951                    } catch (InstallerException e2) {
23952                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23953                    }
23954                }
23955            }
23956        }
23957        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23958            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23959            for (File file : files) {
23960                final String packageName = file.getName();
23961                try {
23962                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23963                } catch (PackageManagerException e) {
23964                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23965                    try {
23966                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23967                                StorageManager.FLAG_STORAGE_DE, 0);
23968                    } catch (InstallerException e2) {
23969                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23970                    }
23971                }
23972            }
23973        }
23974
23975        // Ensure that data directories are ready to roll for all packages
23976        // installed for this volume and user
23977        final List<PackageSetting> packages;
23978        synchronized (mPackages) {
23979            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23980        }
23981        int preparedCount = 0;
23982        for (PackageSetting ps : packages) {
23983            final String packageName = ps.name;
23984            if (ps.pkg == null) {
23985                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23986                // TODO: might be due to legacy ASEC apps; we should circle back
23987                // and reconcile again once they're scanned
23988                continue;
23989            }
23990            // Skip non-core apps if requested
23991            if (onlyCoreApps && !ps.pkg.coreApp) {
23992                result.add(packageName);
23993                continue;
23994            }
23995
23996            if (ps.getInstalled(userId)) {
23997                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23998                preparedCount++;
23999            }
24000        }
24001
24002        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
24003        return result;
24004    }
24005
24006    /**
24007     * Prepare app data for the given app just after it was installed or
24008     * upgraded. This method carefully only touches users that it's installed
24009     * for, and it forces a restorecon to handle any seinfo changes.
24010     * <p>
24011     * Verifies that directories exist and that ownership and labeling is
24012     * correct for all installed apps. If there is an ownership mismatch, it
24013     * will try recovering system apps by wiping data; third-party app data is
24014     * left intact.
24015     * <p>
24016     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
24017     */
24018    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
24019        final PackageSetting ps;
24020        synchronized (mPackages) {
24021            ps = mSettings.mPackages.get(pkg.packageName);
24022            mSettings.writeKernelMappingLPr(ps);
24023        }
24024
24025        final UserManager um = mContext.getSystemService(UserManager.class);
24026        UserManagerInternal umInternal = getUserManagerInternal();
24027        for (UserInfo user : um.getUsers()) {
24028            final int flags;
24029            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
24030                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
24031            } else if (umInternal.isUserRunning(user.id)) {
24032                flags = StorageManager.FLAG_STORAGE_DE;
24033            } else {
24034                continue;
24035            }
24036
24037            if (ps.getInstalled(user.id)) {
24038                // TODO: when user data is locked, mark that we're still dirty
24039                prepareAppDataLIF(pkg, user.id, flags);
24040            }
24041        }
24042    }
24043
24044    /**
24045     * Prepare app data for the given app.
24046     * <p>
24047     * Verifies that directories exist and that ownership and labeling is
24048     * correct for all installed apps. If there is an ownership mismatch, this
24049     * will try recovering system apps by wiping data; third-party app data is
24050     * left intact.
24051     */
24052    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
24053        if (pkg == null) {
24054            Slog.wtf(TAG, "Package was null!", new Throwable());
24055            return;
24056        }
24057        prepareAppDataLeafLIF(pkg, userId, flags);
24058        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24059        for (int i = 0; i < childCount; i++) {
24060            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
24061        }
24062    }
24063
24064    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
24065            boolean maybeMigrateAppData) {
24066        prepareAppDataLIF(pkg, userId, flags);
24067
24068        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
24069            // We may have just shuffled around app data directories, so
24070            // prepare them one more time
24071            prepareAppDataLIF(pkg, userId, flags);
24072        }
24073    }
24074
24075    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24076        if (DEBUG_APP_DATA) {
24077            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
24078                    + Integer.toHexString(flags));
24079        }
24080
24081        final String volumeUuid = pkg.volumeUuid;
24082        final String packageName = pkg.packageName;
24083        final ApplicationInfo app = pkg.applicationInfo;
24084        final int appId = UserHandle.getAppId(app.uid);
24085
24086        Preconditions.checkNotNull(app.seInfo);
24087
24088        long ceDataInode = -1;
24089        try {
24090            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24091                    appId, app.seInfo, app.targetSdkVersion);
24092        } catch (InstallerException e) {
24093            if (app.isSystemApp()) {
24094                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
24095                        + ", but trying to recover: " + e);
24096                destroyAppDataLeafLIF(pkg, userId, flags);
24097                try {
24098                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24099                            appId, app.seInfo, app.targetSdkVersion);
24100                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
24101                } catch (InstallerException e2) {
24102                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
24103                }
24104            } else {
24105                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
24106            }
24107        }
24108
24109        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
24110            // TODO: mark this structure as dirty so we persist it!
24111            synchronized (mPackages) {
24112                final PackageSetting ps = mSettings.mPackages.get(packageName);
24113                if (ps != null) {
24114                    ps.setCeDataInode(ceDataInode, userId);
24115                }
24116            }
24117        }
24118
24119        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24120    }
24121
24122    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
24123        if (pkg == null) {
24124            Slog.wtf(TAG, "Package was null!", new Throwable());
24125            return;
24126        }
24127        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24128        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24129        for (int i = 0; i < childCount; i++) {
24130            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
24131        }
24132    }
24133
24134    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24135        final String volumeUuid = pkg.volumeUuid;
24136        final String packageName = pkg.packageName;
24137        final ApplicationInfo app = pkg.applicationInfo;
24138
24139        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24140            // Create a native library symlink only if we have native libraries
24141            // and if the native libraries are 32 bit libraries. We do not provide
24142            // this symlink for 64 bit libraries.
24143            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24144                final String nativeLibPath = app.nativeLibraryDir;
24145                try {
24146                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24147                            nativeLibPath, userId);
24148                } catch (InstallerException e) {
24149                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24150                }
24151            }
24152        }
24153    }
24154
24155    /**
24156     * For system apps on non-FBE devices, this method migrates any existing
24157     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24158     * requested by the app.
24159     */
24160    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24161        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24162                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24163            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24164                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24165            try {
24166                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24167                        storageTarget);
24168            } catch (InstallerException e) {
24169                logCriticalInfo(Log.WARN,
24170                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24171            }
24172            return true;
24173        } else {
24174            return false;
24175        }
24176    }
24177
24178    public PackageFreezer freezePackage(String packageName, String killReason) {
24179        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24180    }
24181
24182    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24183        return new PackageFreezer(packageName, userId, killReason);
24184    }
24185
24186    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24187            String killReason) {
24188        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24189    }
24190
24191    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24192            String killReason) {
24193        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24194            return new PackageFreezer();
24195        } else {
24196            return freezePackage(packageName, userId, killReason);
24197        }
24198    }
24199
24200    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24201            String killReason) {
24202        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24203    }
24204
24205    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24206            String killReason) {
24207        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24208            return new PackageFreezer();
24209        } else {
24210            return freezePackage(packageName, userId, killReason);
24211        }
24212    }
24213
24214    /**
24215     * Class that freezes and kills the given package upon creation, and
24216     * unfreezes it upon closing. This is typically used when doing surgery on
24217     * app code/data to prevent the app from running while you're working.
24218     */
24219    private class PackageFreezer implements AutoCloseable {
24220        private final String mPackageName;
24221        private final PackageFreezer[] mChildren;
24222
24223        private final boolean mWeFroze;
24224
24225        private final AtomicBoolean mClosed = new AtomicBoolean();
24226        private final CloseGuard mCloseGuard = CloseGuard.get();
24227
24228        /**
24229         * Create and return a stub freezer that doesn't actually do anything,
24230         * typically used when someone requested
24231         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24232         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24233         */
24234        public PackageFreezer() {
24235            mPackageName = null;
24236            mChildren = null;
24237            mWeFroze = false;
24238            mCloseGuard.open("close");
24239        }
24240
24241        public PackageFreezer(String packageName, int userId, String killReason) {
24242            synchronized (mPackages) {
24243                mPackageName = packageName;
24244                mWeFroze = mFrozenPackages.add(mPackageName);
24245
24246                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24247                if (ps != null) {
24248                    killApplication(ps.name, ps.appId, userId, killReason);
24249                }
24250
24251                final PackageParser.Package p = mPackages.get(packageName);
24252                if (p != null && p.childPackages != null) {
24253                    final int N = p.childPackages.size();
24254                    mChildren = new PackageFreezer[N];
24255                    for (int i = 0; i < N; i++) {
24256                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24257                                userId, killReason);
24258                    }
24259                } else {
24260                    mChildren = null;
24261                }
24262            }
24263            mCloseGuard.open("close");
24264        }
24265
24266        @Override
24267        protected void finalize() throws Throwable {
24268            try {
24269                if (mCloseGuard != null) {
24270                    mCloseGuard.warnIfOpen();
24271                }
24272
24273                close();
24274            } finally {
24275                super.finalize();
24276            }
24277        }
24278
24279        @Override
24280        public void close() {
24281            mCloseGuard.close();
24282            if (mClosed.compareAndSet(false, true)) {
24283                synchronized (mPackages) {
24284                    if (mWeFroze) {
24285                        mFrozenPackages.remove(mPackageName);
24286                    }
24287
24288                    if (mChildren != null) {
24289                        for (PackageFreezer freezer : mChildren) {
24290                            freezer.close();
24291                        }
24292                    }
24293                }
24294            }
24295        }
24296    }
24297
24298    /**
24299     * Verify that given package is currently frozen.
24300     */
24301    private void checkPackageFrozen(String packageName) {
24302        synchronized (mPackages) {
24303            if (!mFrozenPackages.contains(packageName)) {
24304                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24305            }
24306        }
24307    }
24308
24309    @Override
24310    public int movePackage(final String packageName, final String volumeUuid) {
24311        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24312
24313        final int callingUid = Binder.getCallingUid();
24314        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24315        final int moveId = mNextMoveId.getAndIncrement();
24316        mHandler.post(new Runnable() {
24317            @Override
24318            public void run() {
24319                try {
24320                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24321                } catch (PackageManagerException e) {
24322                    Slog.w(TAG, "Failed to move " + packageName, e);
24323                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24324                }
24325            }
24326        });
24327        return moveId;
24328    }
24329
24330    private void movePackageInternal(final String packageName, final String volumeUuid,
24331            final int moveId, final int callingUid, UserHandle user)
24332                    throws PackageManagerException {
24333        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24334        final PackageManager pm = mContext.getPackageManager();
24335
24336        final boolean currentAsec;
24337        final String currentVolumeUuid;
24338        final File codeFile;
24339        final String installerPackageName;
24340        final String packageAbiOverride;
24341        final int appId;
24342        final String seinfo;
24343        final String label;
24344        final int targetSdkVersion;
24345        final PackageFreezer freezer;
24346        final int[] installedUserIds;
24347
24348        // reader
24349        synchronized (mPackages) {
24350            final PackageParser.Package pkg = mPackages.get(packageName);
24351            final PackageSetting ps = mSettings.mPackages.get(packageName);
24352            if (pkg == null
24353                    || ps == null
24354                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24355                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24356            }
24357            if (pkg.applicationInfo.isSystemApp()) {
24358                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24359                        "Cannot move system application");
24360            }
24361
24362            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24363            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24364                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24365            if (isInternalStorage && !allow3rdPartyOnInternal) {
24366                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24367                        "3rd party apps are not allowed on internal storage");
24368            }
24369
24370            if (pkg.applicationInfo.isExternalAsec()) {
24371                currentAsec = true;
24372                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24373            } else if (pkg.applicationInfo.isForwardLocked()) {
24374                currentAsec = true;
24375                currentVolumeUuid = "forward_locked";
24376            } else {
24377                currentAsec = false;
24378                currentVolumeUuid = ps.volumeUuid;
24379
24380                final File probe = new File(pkg.codePath);
24381                final File probeOat = new File(probe, "oat");
24382                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24383                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24384                            "Move only supported for modern cluster style installs");
24385                }
24386            }
24387
24388            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24389                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24390                        "Package already moved to " + volumeUuid);
24391            }
24392            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24393                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24394                        "Device admin cannot be moved");
24395            }
24396
24397            if (mFrozenPackages.contains(packageName)) {
24398                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24399                        "Failed to move already frozen package");
24400            }
24401
24402            codeFile = new File(pkg.codePath);
24403            installerPackageName = ps.installerPackageName;
24404            packageAbiOverride = ps.cpuAbiOverrideString;
24405            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24406            seinfo = pkg.applicationInfo.seInfo;
24407            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24408            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24409            freezer = freezePackage(packageName, "movePackageInternal");
24410            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24411        }
24412
24413        final Bundle extras = new Bundle();
24414        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24415        extras.putString(Intent.EXTRA_TITLE, label);
24416        mMoveCallbacks.notifyCreated(moveId, extras);
24417
24418        int installFlags;
24419        final boolean moveCompleteApp;
24420        final File measurePath;
24421
24422        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24423            installFlags = INSTALL_INTERNAL;
24424            moveCompleteApp = !currentAsec;
24425            measurePath = Environment.getDataAppDirectory(volumeUuid);
24426        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24427            installFlags = INSTALL_EXTERNAL;
24428            moveCompleteApp = false;
24429            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24430        } else {
24431            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24432            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24433                    || !volume.isMountedWritable()) {
24434                freezer.close();
24435                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24436                        "Move location not mounted private volume");
24437            }
24438
24439            Preconditions.checkState(!currentAsec);
24440
24441            installFlags = INSTALL_INTERNAL;
24442            moveCompleteApp = true;
24443            measurePath = Environment.getDataAppDirectory(volumeUuid);
24444        }
24445
24446        // If we're moving app data around, we need all the users unlocked
24447        if (moveCompleteApp) {
24448            for (int userId : installedUserIds) {
24449                if (StorageManager.isFileEncryptedNativeOrEmulated()
24450                        && !StorageManager.isUserKeyUnlocked(userId)) {
24451                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24452                            "User " + userId + " must be unlocked");
24453                }
24454            }
24455        }
24456
24457        final PackageStats stats = new PackageStats(null, -1);
24458        synchronized (mInstaller) {
24459            for (int userId : installedUserIds) {
24460                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24461                    freezer.close();
24462                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24463                            "Failed to measure package size");
24464                }
24465            }
24466        }
24467
24468        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24469                + stats.dataSize);
24470
24471        final long startFreeBytes = measurePath.getUsableSpace();
24472        final long sizeBytes;
24473        if (moveCompleteApp) {
24474            sizeBytes = stats.codeSize + stats.dataSize;
24475        } else {
24476            sizeBytes = stats.codeSize;
24477        }
24478
24479        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24480            freezer.close();
24481            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24482                    "Not enough free space to move");
24483        }
24484
24485        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24486
24487        final CountDownLatch installedLatch = new CountDownLatch(1);
24488        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24489            @Override
24490            public void onUserActionRequired(Intent intent) throws RemoteException {
24491                throw new IllegalStateException();
24492            }
24493
24494            @Override
24495            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24496                    Bundle extras) throws RemoteException {
24497                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24498                        + PackageManager.installStatusToString(returnCode, msg));
24499
24500                installedLatch.countDown();
24501                freezer.close();
24502
24503                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24504                switch (status) {
24505                    case PackageInstaller.STATUS_SUCCESS:
24506                        mMoveCallbacks.notifyStatusChanged(moveId,
24507                                PackageManager.MOVE_SUCCEEDED);
24508                        break;
24509                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24510                        mMoveCallbacks.notifyStatusChanged(moveId,
24511                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24512                        break;
24513                    default:
24514                        mMoveCallbacks.notifyStatusChanged(moveId,
24515                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24516                        break;
24517                }
24518            }
24519        };
24520
24521        final MoveInfo move;
24522        if (moveCompleteApp) {
24523            // Kick off a thread to report progress estimates
24524            new Thread() {
24525                @Override
24526                public void run() {
24527                    while (true) {
24528                        try {
24529                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24530                                break;
24531                            }
24532                        } catch (InterruptedException ignored) {
24533                        }
24534
24535                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24536                        final int progress = 10 + (int) MathUtils.constrain(
24537                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24538                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24539                    }
24540                }
24541            }.start();
24542
24543            final String dataAppName = codeFile.getName();
24544            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24545                    dataAppName, appId, seinfo, targetSdkVersion);
24546        } else {
24547            move = null;
24548        }
24549
24550        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24551
24552        final Message msg = mHandler.obtainMessage(INIT_COPY);
24553        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24554        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24555                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24556                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24557                PackageManager.INSTALL_REASON_UNKNOWN);
24558        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24559        msg.obj = params;
24560
24561        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24562                System.identityHashCode(msg.obj));
24563        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24564                System.identityHashCode(msg.obj));
24565
24566        mHandler.sendMessage(msg);
24567    }
24568
24569    @Override
24570    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24571        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24572
24573        final int realMoveId = mNextMoveId.getAndIncrement();
24574        final Bundle extras = new Bundle();
24575        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24576        mMoveCallbacks.notifyCreated(realMoveId, extras);
24577
24578        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24579            @Override
24580            public void onCreated(int moveId, Bundle extras) {
24581                // Ignored
24582            }
24583
24584            @Override
24585            public void onStatusChanged(int moveId, int status, long estMillis) {
24586                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24587            }
24588        };
24589
24590        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24591        storage.setPrimaryStorageUuid(volumeUuid, callback);
24592        return realMoveId;
24593    }
24594
24595    @Override
24596    public int getMoveStatus(int moveId) {
24597        mContext.enforceCallingOrSelfPermission(
24598                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24599        return mMoveCallbacks.mLastStatus.get(moveId);
24600    }
24601
24602    @Override
24603    public void registerMoveCallback(IPackageMoveObserver callback) {
24604        mContext.enforceCallingOrSelfPermission(
24605                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24606        mMoveCallbacks.register(callback);
24607    }
24608
24609    @Override
24610    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24611        mContext.enforceCallingOrSelfPermission(
24612                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24613        mMoveCallbacks.unregister(callback);
24614    }
24615
24616    @Override
24617    public boolean setInstallLocation(int loc) {
24618        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24619                null);
24620        if (getInstallLocation() == loc) {
24621            return true;
24622        }
24623        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24624                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24625            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24626                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24627            return true;
24628        }
24629        return false;
24630   }
24631
24632    @Override
24633    public int getInstallLocation() {
24634        // allow instant app access
24635        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24636                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24637                PackageHelper.APP_INSTALL_AUTO);
24638    }
24639
24640    /** Called by UserManagerService */
24641    void cleanUpUser(UserManagerService userManager, int userHandle) {
24642        synchronized (mPackages) {
24643            mDirtyUsers.remove(userHandle);
24644            mUserNeedsBadging.delete(userHandle);
24645            mSettings.removeUserLPw(userHandle);
24646            mPendingBroadcasts.remove(userHandle);
24647            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24648            removeUnusedPackagesLPw(userManager, userHandle);
24649        }
24650    }
24651
24652    /**
24653     * We're removing userHandle and would like to remove any downloaded packages
24654     * that are no longer in use by any other user.
24655     * @param userHandle the user being removed
24656     */
24657    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24658        final boolean DEBUG_CLEAN_APKS = false;
24659        int [] users = userManager.getUserIds();
24660        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24661        while (psit.hasNext()) {
24662            PackageSetting ps = psit.next();
24663            if (ps.pkg == null) {
24664                continue;
24665            }
24666            final String packageName = ps.pkg.packageName;
24667            // Skip over if system app
24668            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24669                continue;
24670            }
24671            if (DEBUG_CLEAN_APKS) {
24672                Slog.i(TAG, "Checking package " + packageName);
24673            }
24674            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24675            if (keep) {
24676                if (DEBUG_CLEAN_APKS) {
24677                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24678                }
24679            } else {
24680                for (int i = 0; i < users.length; i++) {
24681                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24682                        keep = true;
24683                        if (DEBUG_CLEAN_APKS) {
24684                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24685                                    + users[i]);
24686                        }
24687                        break;
24688                    }
24689                }
24690            }
24691            if (!keep) {
24692                if (DEBUG_CLEAN_APKS) {
24693                    Slog.i(TAG, "  Removing package " + packageName);
24694                }
24695                mHandler.post(new Runnable() {
24696                    public void run() {
24697                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24698                                userHandle, 0);
24699                    } //end run
24700                });
24701            }
24702        }
24703    }
24704
24705    /** Called by UserManagerService */
24706    void createNewUser(int userId, String[] disallowedPackages) {
24707        synchronized (mInstallLock) {
24708            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24709        }
24710        synchronized (mPackages) {
24711            scheduleWritePackageRestrictionsLocked(userId);
24712            scheduleWritePackageListLocked(userId);
24713            applyFactoryDefaultBrowserLPw(userId);
24714            primeDomainVerificationsLPw(userId);
24715        }
24716    }
24717
24718    void onNewUserCreated(final int userId) {
24719        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24720        // If permission review for legacy apps is required, we represent
24721        // dagerous permissions for such apps as always granted runtime
24722        // permissions to keep per user flag state whether review is needed.
24723        // Hence, if a new user is added we have to propagate dangerous
24724        // permission grants for these legacy apps.
24725        if (mPermissionReviewRequired) {
24726            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24727                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24728        }
24729    }
24730
24731    @Override
24732    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24733        mContext.enforceCallingOrSelfPermission(
24734                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24735                "Only package verification agents can read the verifier device identity");
24736
24737        synchronized (mPackages) {
24738            return mSettings.getVerifierDeviceIdentityLPw();
24739        }
24740    }
24741
24742    @Override
24743    public void setPermissionEnforced(String permission, boolean enforced) {
24744        // TODO: Now that we no longer change GID for storage, this should to away.
24745        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24746                "setPermissionEnforced");
24747        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24748            synchronized (mPackages) {
24749                if (mSettings.mReadExternalStorageEnforced == null
24750                        || mSettings.mReadExternalStorageEnforced != enforced) {
24751                    mSettings.mReadExternalStorageEnforced = enforced;
24752                    mSettings.writeLPr();
24753                }
24754            }
24755            // kill any non-foreground processes so we restart them and
24756            // grant/revoke the GID.
24757            final IActivityManager am = ActivityManager.getService();
24758            if (am != null) {
24759                final long token = Binder.clearCallingIdentity();
24760                try {
24761                    am.killProcessesBelowForeground("setPermissionEnforcement");
24762                } catch (RemoteException e) {
24763                } finally {
24764                    Binder.restoreCallingIdentity(token);
24765                }
24766            }
24767        } else {
24768            throw new IllegalArgumentException("No selective enforcement for " + permission);
24769        }
24770    }
24771
24772    @Override
24773    @Deprecated
24774    public boolean isPermissionEnforced(String permission) {
24775        // allow instant applications
24776        return true;
24777    }
24778
24779    @Override
24780    public boolean isStorageLow() {
24781        // allow instant applications
24782        final long token = Binder.clearCallingIdentity();
24783        try {
24784            final DeviceStorageMonitorInternal
24785                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24786            if (dsm != null) {
24787                return dsm.isMemoryLow();
24788            } else {
24789                return false;
24790            }
24791        } finally {
24792            Binder.restoreCallingIdentity(token);
24793        }
24794    }
24795
24796    @Override
24797    public IPackageInstaller getPackageInstaller() {
24798        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24799            return null;
24800        }
24801        return mInstallerService;
24802    }
24803
24804    private boolean userNeedsBadging(int userId) {
24805        int index = mUserNeedsBadging.indexOfKey(userId);
24806        if (index < 0) {
24807            final UserInfo userInfo;
24808            final long token = Binder.clearCallingIdentity();
24809            try {
24810                userInfo = sUserManager.getUserInfo(userId);
24811            } finally {
24812                Binder.restoreCallingIdentity(token);
24813            }
24814            final boolean b;
24815            if (userInfo != null && userInfo.isManagedProfile()) {
24816                b = true;
24817            } else {
24818                b = false;
24819            }
24820            mUserNeedsBadging.put(userId, b);
24821            return b;
24822        }
24823        return mUserNeedsBadging.valueAt(index);
24824    }
24825
24826    @Override
24827    public KeySet getKeySetByAlias(String packageName, String alias) {
24828        if (packageName == null || alias == null) {
24829            return null;
24830        }
24831        synchronized(mPackages) {
24832            final PackageParser.Package pkg = mPackages.get(packageName);
24833            if (pkg == null) {
24834                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24835                throw new IllegalArgumentException("Unknown package: " + packageName);
24836            }
24837            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24838            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24839                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24840                throw new IllegalArgumentException("Unknown package: " + packageName);
24841            }
24842            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24843            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24844        }
24845    }
24846
24847    @Override
24848    public KeySet getSigningKeySet(String packageName) {
24849        if (packageName == null) {
24850            return null;
24851        }
24852        synchronized(mPackages) {
24853            final int callingUid = Binder.getCallingUid();
24854            final int callingUserId = UserHandle.getUserId(callingUid);
24855            final PackageParser.Package pkg = mPackages.get(packageName);
24856            if (pkg == null) {
24857                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24858                throw new IllegalArgumentException("Unknown package: " + packageName);
24859            }
24860            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24861            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24862                // filter and pretend the package doesn't exist
24863                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24864                        + ", uid:" + callingUid);
24865                throw new IllegalArgumentException("Unknown package: " + packageName);
24866            }
24867            if (pkg.applicationInfo.uid != callingUid
24868                    && Process.SYSTEM_UID != callingUid) {
24869                throw new SecurityException("May not access signing KeySet of other apps.");
24870            }
24871            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24872            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24873        }
24874    }
24875
24876    @Override
24877    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24878        final int callingUid = Binder.getCallingUid();
24879        if (getInstantAppPackageName(callingUid) != null) {
24880            return false;
24881        }
24882        if (packageName == null || ks == null) {
24883            return false;
24884        }
24885        synchronized(mPackages) {
24886            final PackageParser.Package pkg = mPackages.get(packageName);
24887            if (pkg == null
24888                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24889                            UserHandle.getUserId(callingUid))) {
24890                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24891                throw new IllegalArgumentException("Unknown package: " + packageName);
24892            }
24893            IBinder ksh = ks.getToken();
24894            if (ksh instanceof KeySetHandle) {
24895                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24896                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24897            }
24898            return false;
24899        }
24900    }
24901
24902    @Override
24903    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24904        final int callingUid = Binder.getCallingUid();
24905        if (getInstantAppPackageName(callingUid) != null) {
24906            return false;
24907        }
24908        if (packageName == null || ks == null) {
24909            return false;
24910        }
24911        synchronized(mPackages) {
24912            final PackageParser.Package pkg = mPackages.get(packageName);
24913            if (pkg == null
24914                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24915                            UserHandle.getUserId(callingUid))) {
24916                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24917                throw new IllegalArgumentException("Unknown package: " + packageName);
24918            }
24919            IBinder ksh = ks.getToken();
24920            if (ksh instanceof KeySetHandle) {
24921                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24922                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24923            }
24924            return false;
24925        }
24926    }
24927
24928    private void deletePackageIfUnusedLPr(final String packageName) {
24929        PackageSetting ps = mSettings.mPackages.get(packageName);
24930        if (ps == null) {
24931            return;
24932        }
24933        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24934            // TODO Implement atomic delete if package is unused
24935            // It is currently possible that the package will be deleted even if it is installed
24936            // after this method returns.
24937            mHandler.post(new Runnable() {
24938                public void run() {
24939                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24940                            0, PackageManager.DELETE_ALL_USERS);
24941                }
24942            });
24943        }
24944    }
24945
24946    /**
24947     * Check and throw if the given before/after packages would be considered a
24948     * downgrade.
24949     */
24950    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24951            throws PackageManagerException {
24952        if (after.versionCode < before.mVersionCode) {
24953            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24954                    "Update version code " + after.versionCode + " is older than current "
24955                    + before.mVersionCode);
24956        } else if (after.versionCode == before.mVersionCode) {
24957            if (after.baseRevisionCode < before.baseRevisionCode) {
24958                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24959                        "Update base revision code " + after.baseRevisionCode
24960                        + " is older than current " + before.baseRevisionCode);
24961            }
24962
24963            if (!ArrayUtils.isEmpty(after.splitNames)) {
24964                for (int i = 0; i < after.splitNames.length; i++) {
24965                    final String splitName = after.splitNames[i];
24966                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24967                    if (j != -1) {
24968                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24969                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24970                                    "Update split " + splitName + " revision code "
24971                                    + after.splitRevisionCodes[i] + " is older than current "
24972                                    + before.splitRevisionCodes[j]);
24973                        }
24974                    }
24975                }
24976            }
24977        }
24978    }
24979
24980    private static class MoveCallbacks extends Handler {
24981        private static final int MSG_CREATED = 1;
24982        private static final int MSG_STATUS_CHANGED = 2;
24983
24984        private final RemoteCallbackList<IPackageMoveObserver>
24985                mCallbacks = new RemoteCallbackList<>();
24986
24987        private final SparseIntArray mLastStatus = new SparseIntArray();
24988
24989        public MoveCallbacks(Looper looper) {
24990            super(looper);
24991        }
24992
24993        public void register(IPackageMoveObserver callback) {
24994            mCallbacks.register(callback);
24995        }
24996
24997        public void unregister(IPackageMoveObserver callback) {
24998            mCallbacks.unregister(callback);
24999        }
25000
25001        @Override
25002        public void handleMessage(Message msg) {
25003            final SomeArgs args = (SomeArgs) msg.obj;
25004            final int n = mCallbacks.beginBroadcast();
25005            for (int i = 0; i < n; i++) {
25006                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
25007                try {
25008                    invokeCallback(callback, msg.what, args);
25009                } catch (RemoteException ignored) {
25010                }
25011            }
25012            mCallbacks.finishBroadcast();
25013            args.recycle();
25014        }
25015
25016        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
25017                throws RemoteException {
25018            switch (what) {
25019                case MSG_CREATED: {
25020                    callback.onCreated(args.argi1, (Bundle) args.arg2);
25021                    break;
25022                }
25023                case MSG_STATUS_CHANGED: {
25024                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
25025                    break;
25026                }
25027            }
25028        }
25029
25030        private void notifyCreated(int moveId, Bundle extras) {
25031            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
25032
25033            final SomeArgs args = SomeArgs.obtain();
25034            args.argi1 = moveId;
25035            args.arg2 = extras;
25036            obtainMessage(MSG_CREATED, args).sendToTarget();
25037        }
25038
25039        private void notifyStatusChanged(int moveId, int status) {
25040            notifyStatusChanged(moveId, status, -1);
25041        }
25042
25043        private void notifyStatusChanged(int moveId, int status, long estMillis) {
25044            Slog.v(TAG, "Move " + moveId + " status " + status);
25045
25046            final SomeArgs args = SomeArgs.obtain();
25047            args.argi1 = moveId;
25048            args.argi2 = status;
25049            args.arg3 = estMillis;
25050            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
25051
25052            synchronized (mLastStatus) {
25053                mLastStatus.put(moveId, status);
25054            }
25055        }
25056    }
25057
25058    private final static class OnPermissionChangeListeners extends Handler {
25059        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
25060
25061        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
25062                new RemoteCallbackList<>();
25063
25064        public OnPermissionChangeListeners(Looper looper) {
25065            super(looper);
25066        }
25067
25068        @Override
25069        public void handleMessage(Message msg) {
25070            switch (msg.what) {
25071                case MSG_ON_PERMISSIONS_CHANGED: {
25072                    final int uid = msg.arg1;
25073                    handleOnPermissionsChanged(uid);
25074                } break;
25075            }
25076        }
25077
25078        public void addListenerLocked(IOnPermissionsChangeListener listener) {
25079            mPermissionListeners.register(listener);
25080
25081        }
25082
25083        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
25084            mPermissionListeners.unregister(listener);
25085        }
25086
25087        public void onPermissionsChanged(int uid) {
25088            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
25089                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
25090            }
25091        }
25092
25093        private void handleOnPermissionsChanged(int uid) {
25094            final int count = mPermissionListeners.beginBroadcast();
25095            try {
25096                for (int i = 0; i < count; i++) {
25097                    IOnPermissionsChangeListener callback = mPermissionListeners
25098                            .getBroadcastItem(i);
25099                    try {
25100                        callback.onPermissionsChanged(uid);
25101                    } catch (RemoteException e) {
25102                        Log.e(TAG, "Permission listener is dead", e);
25103                    }
25104                }
25105            } finally {
25106                mPermissionListeners.finishBroadcast();
25107            }
25108        }
25109    }
25110
25111    private class PackageManagerNative extends IPackageManagerNative.Stub {
25112        @Override
25113        public String[] getNamesForUids(int[] uids) throws RemoteException {
25114            final String[] results = PackageManagerService.this.getNamesForUids(uids);
25115            // massage results so they can be parsed by the native binder
25116            for (int i = results.length - 1; i >= 0; --i) {
25117                if (results[i] == null) {
25118                    results[i] = "";
25119                }
25120            }
25121            return results;
25122        }
25123    }
25124
25125    private class PackageManagerInternalImpl extends PackageManagerInternal {
25126        @Override
25127        public void setLocationPackagesProvider(PackagesProvider provider) {
25128            synchronized (mPackages) {
25129                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
25130            }
25131        }
25132
25133        @Override
25134        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25135            synchronized (mPackages) {
25136                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
25137            }
25138        }
25139
25140        @Override
25141        public void setSmsAppPackagesProvider(PackagesProvider provider) {
25142            synchronized (mPackages) {
25143                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
25144            }
25145        }
25146
25147        @Override
25148        public void setDialerAppPackagesProvider(PackagesProvider provider) {
25149            synchronized (mPackages) {
25150                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
25151            }
25152        }
25153
25154        @Override
25155        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25156            synchronized (mPackages) {
25157                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
25158            }
25159        }
25160
25161        @Override
25162        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25163            synchronized (mPackages) {
25164                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25165            }
25166        }
25167
25168        @Override
25169        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25170            synchronized (mPackages) {
25171                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25172                        packageName, userId);
25173            }
25174        }
25175
25176        @Override
25177        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25178            synchronized (mPackages) {
25179                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25180                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25181                        packageName, userId);
25182            }
25183        }
25184
25185        @Override
25186        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25187            synchronized (mPackages) {
25188                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25189                        packageName, userId);
25190            }
25191        }
25192
25193        @Override
25194        public void setKeepUninstalledPackages(final List<String> packageList) {
25195            Preconditions.checkNotNull(packageList);
25196            List<String> removedFromList = null;
25197            synchronized (mPackages) {
25198                if (mKeepUninstalledPackages != null) {
25199                    final int packagesCount = mKeepUninstalledPackages.size();
25200                    for (int i = 0; i < packagesCount; i++) {
25201                        String oldPackage = mKeepUninstalledPackages.get(i);
25202                        if (packageList != null && packageList.contains(oldPackage)) {
25203                            continue;
25204                        }
25205                        if (removedFromList == null) {
25206                            removedFromList = new ArrayList<>();
25207                        }
25208                        removedFromList.add(oldPackage);
25209                    }
25210                }
25211                mKeepUninstalledPackages = new ArrayList<>(packageList);
25212                if (removedFromList != null) {
25213                    final int removedCount = removedFromList.size();
25214                    for (int i = 0; i < removedCount; i++) {
25215                        deletePackageIfUnusedLPr(removedFromList.get(i));
25216                    }
25217                }
25218            }
25219        }
25220
25221        @Override
25222        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25223            synchronized (mPackages) {
25224                // If we do not support permission review, done.
25225                if (!mPermissionReviewRequired) {
25226                    return false;
25227                }
25228
25229                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25230                if (packageSetting == null) {
25231                    return false;
25232                }
25233
25234                // Permission review applies only to apps not supporting the new permission model.
25235                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25236                    return false;
25237                }
25238
25239                // Legacy apps have the permission and get user consent on launch.
25240                PermissionsState permissionsState = packageSetting.getPermissionsState();
25241                return permissionsState.isPermissionReviewRequired(userId);
25242            }
25243        }
25244
25245        @Override
25246        public PackageInfo getPackageInfo(
25247                String packageName, int flags, int filterCallingUid, int userId) {
25248            return PackageManagerService.this
25249                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25250                            flags, filterCallingUid, userId);
25251        }
25252
25253        @Override
25254        public ApplicationInfo getApplicationInfo(
25255                String packageName, int flags, int filterCallingUid, int userId) {
25256            return PackageManagerService.this
25257                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25258        }
25259
25260        @Override
25261        public ActivityInfo getActivityInfo(
25262                ComponentName component, int flags, int filterCallingUid, int userId) {
25263            return PackageManagerService.this
25264                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25265        }
25266
25267        @Override
25268        public List<ResolveInfo> queryIntentActivities(
25269                Intent intent, int flags, int filterCallingUid, int userId) {
25270            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25271            return PackageManagerService.this
25272                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25273                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25274        }
25275
25276        @Override
25277        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25278                int userId) {
25279            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25280        }
25281
25282        @Override
25283        public void setDeviceAndProfileOwnerPackages(
25284                int deviceOwnerUserId, String deviceOwnerPackage,
25285                SparseArray<String> profileOwnerPackages) {
25286            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25287                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25288        }
25289
25290        @Override
25291        public boolean isPackageDataProtected(int userId, String packageName) {
25292            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25293        }
25294
25295        @Override
25296        public boolean isPackageEphemeral(int userId, String packageName) {
25297            synchronized (mPackages) {
25298                final PackageSetting ps = mSettings.mPackages.get(packageName);
25299                return ps != null ? ps.getInstantApp(userId) : false;
25300            }
25301        }
25302
25303        @Override
25304        public boolean wasPackageEverLaunched(String packageName, int userId) {
25305            synchronized (mPackages) {
25306                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25307            }
25308        }
25309
25310        @Override
25311        public void grantRuntimePermission(String packageName, String name, int userId,
25312                boolean overridePolicy) {
25313            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25314                    overridePolicy);
25315        }
25316
25317        @Override
25318        public void revokeRuntimePermission(String packageName, String name, int userId,
25319                boolean overridePolicy) {
25320            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25321                    overridePolicy);
25322        }
25323
25324        @Override
25325        public String getNameForUid(int uid) {
25326            return PackageManagerService.this.getNameForUid(uid);
25327        }
25328
25329        @Override
25330        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25331                Intent origIntent, String resolvedType, String callingPackage,
25332                Bundle verificationBundle, int userId) {
25333            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25334                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25335                    userId);
25336        }
25337
25338        @Override
25339        public void grantEphemeralAccess(int userId, Intent intent,
25340                int targetAppId, int ephemeralAppId) {
25341            synchronized (mPackages) {
25342                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25343                        targetAppId, ephemeralAppId);
25344            }
25345        }
25346
25347        @Override
25348        public boolean isInstantAppInstallerComponent(ComponentName component) {
25349            synchronized (mPackages) {
25350                return mInstantAppInstallerActivity != null
25351                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25352            }
25353        }
25354
25355        @Override
25356        public void pruneInstantApps() {
25357            mInstantAppRegistry.pruneInstantApps();
25358        }
25359
25360        @Override
25361        public String getSetupWizardPackageName() {
25362            return mSetupWizardPackage;
25363        }
25364
25365        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25366            if (policy != null) {
25367                mExternalSourcesPolicy = policy;
25368            }
25369        }
25370
25371        @Override
25372        public boolean isPackagePersistent(String packageName) {
25373            synchronized (mPackages) {
25374                PackageParser.Package pkg = mPackages.get(packageName);
25375                return pkg != null
25376                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25377                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25378                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25379                        : false;
25380            }
25381        }
25382
25383        @Override
25384        public List<PackageInfo> getOverlayPackages(int userId) {
25385            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25386            synchronized (mPackages) {
25387                for (PackageParser.Package p : mPackages.values()) {
25388                    if (p.mOverlayTarget != null) {
25389                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25390                        if (pkg != null) {
25391                            overlayPackages.add(pkg);
25392                        }
25393                    }
25394                }
25395            }
25396            return overlayPackages;
25397        }
25398
25399        @Override
25400        public List<String> getTargetPackageNames(int userId) {
25401            List<String> targetPackages = new ArrayList<>();
25402            synchronized (mPackages) {
25403                for (PackageParser.Package p : mPackages.values()) {
25404                    if (p.mOverlayTarget == null) {
25405                        targetPackages.add(p.packageName);
25406                    }
25407                }
25408            }
25409            return targetPackages;
25410        }
25411
25412        @Override
25413        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25414                @Nullable List<String> overlayPackageNames) {
25415            synchronized (mPackages) {
25416                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25417                    Slog.e(TAG, "failed to find package " + targetPackageName);
25418                    return false;
25419                }
25420                ArrayList<String> overlayPaths = null;
25421                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25422                    final int N = overlayPackageNames.size();
25423                    overlayPaths = new ArrayList<>(N);
25424                    for (int i = 0; i < N; i++) {
25425                        final String packageName = overlayPackageNames.get(i);
25426                        final PackageParser.Package pkg = mPackages.get(packageName);
25427                        if (pkg == null) {
25428                            Slog.e(TAG, "failed to find package " + packageName);
25429                            return false;
25430                        }
25431                        overlayPaths.add(pkg.baseCodePath);
25432                    }
25433                }
25434
25435                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25436                ps.setOverlayPaths(overlayPaths, userId);
25437                return true;
25438            }
25439        }
25440
25441        @Override
25442        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25443                int flags, int userId) {
25444            return resolveIntentInternal(
25445                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25446        }
25447
25448        @Override
25449        public ResolveInfo resolveService(Intent intent, String resolvedType,
25450                int flags, int userId, int callingUid) {
25451            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25452        }
25453
25454        @Override
25455        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25456            synchronized (mPackages) {
25457                mIsolatedOwners.put(isolatedUid, ownerUid);
25458            }
25459        }
25460
25461        @Override
25462        public void removeIsolatedUid(int isolatedUid) {
25463            synchronized (mPackages) {
25464                mIsolatedOwners.delete(isolatedUid);
25465            }
25466        }
25467
25468        @Override
25469        public int getUidTargetSdkVersion(int uid) {
25470            synchronized (mPackages) {
25471                return getUidTargetSdkVersionLockedLPr(uid);
25472            }
25473        }
25474
25475        @Override
25476        public boolean canAccessInstantApps(int callingUid, int userId) {
25477            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25478        }
25479    }
25480
25481    @Override
25482    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25483        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25484        synchronized (mPackages) {
25485            final long identity = Binder.clearCallingIdentity();
25486            try {
25487                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25488                        packageNames, userId);
25489            } finally {
25490                Binder.restoreCallingIdentity(identity);
25491            }
25492        }
25493    }
25494
25495    @Override
25496    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25497        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25498        synchronized (mPackages) {
25499            final long identity = Binder.clearCallingIdentity();
25500            try {
25501                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25502                        packageNames, userId);
25503            } finally {
25504                Binder.restoreCallingIdentity(identity);
25505            }
25506        }
25507    }
25508
25509    private static void enforceSystemOrPhoneCaller(String tag) {
25510        int callingUid = Binder.getCallingUid();
25511        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25512            throw new SecurityException(
25513                    "Cannot call " + tag + " from UID " + callingUid);
25514        }
25515    }
25516
25517    boolean isHistoricalPackageUsageAvailable() {
25518        return mPackageUsage.isHistoricalPackageUsageAvailable();
25519    }
25520
25521    /**
25522     * Return a <b>copy</b> of the collection of packages known to the package manager.
25523     * @return A copy of the values of mPackages.
25524     */
25525    Collection<PackageParser.Package> getPackages() {
25526        synchronized (mPackages) {
25527            return new ArrayList<>(mPackages.values());
25528        }
25529    }
25530
25531    /**
25532     * Logs process start information (including base APK hash) to the security log.
25533     * @hide
25534     */
25535    @Override
25536    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25537            String apkFile, int pid) {
25538        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25539            return;
25540        }
25541        if (!SecurityLog.isLoggingEnabled()) {
25542            return;
25543        }
25544        Bundle data = new Bundle();
25545        data.putLong("startTimestamp", System.currentTimeMillis());
25546        data.putString("processName", processName);
25547        data.putInt("uid", uid);
25548        data.putString("seinfo", seinfo);
25549        data.putString("apkFile", apkFile);
25550        data.putInt("pid", pid);
25551        Message msg = mProcessLoggingHandler.obtainMessage(
25552                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25553        msg.setData(data);
25554        mProcessLoggingHandler.sendMessage(msg);
25555    }
25556
25557    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25558        return mCompilerStats.getPackageStats(pkgName);
25559    }
25560
25561    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25562        return getOrCreateCompilerPackageStats(pkg.packageName);
25563    }
25564
25565    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25566        return mCompilerStats.getOrCreatePackageStats(pkgName);
25567    }
25568
25569    public void deleteCompilerPackageStats(String pkgName) {
25570        mCompilerStats.deletePackageStats(pkgName);
25571    }
25572
25573    @Override
25574    public int getInstallReason(String packageName, int userId) {
25575        final int callingUid = Binder.getCallingUid();
25576        enforceCrossUserPermission(callingUid, userId,
25577                true /* requireFullPermission */, false /* checkShell */,
25578                "get install reason");
25579        synchronized (mPackages) {
25580            final PackageSetting ps = mSettings.mPackages.get(packageName);
25581            if (filterAppAccessLPr(ps, callingUid, userId)) {
25582                return PackageManager.INSTALL_REASON_UNKNOWN;
25583            }
25584            if (ps != null) {
25585                return ps.getInstallReason(userId);
25586            }
25587        }
25588        return PackageManager.INSTALL_REASON_UNKNOWN;
25589    }
25590
25591    @Override
25592    public boolean canRequestPackageInstalls(String packageName, int userId) {
25593        return canRequestPackageInstallsInternal(packageName, 0, userId,
25594                true /* throwIfPermNotDeclared*/);
25595    }
25596
25597    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25598            boolean throwIfPermNotDeclared) {
25599        int callingUid = Binder.getCallingUid();
25600        int uid = getPackageUid(packageName, 0, userId);
25601        if (callingUid != uid && callingUid != Process.ROOT_UID
25602                && callingUid != Process.SYSTEM_UID) {
25603            throw new SecurityException(
25604                    "Caller uid " + callingUid + " does not own package " + packageName);
25605        }
25606        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25607        if (info == null) {
25608            return false;
25609        }
25610        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25611            return false;
25612        }
25613        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25614        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25615        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25616            if (throwIfPermNotDeclared) {
25617                throw new SecurityException("Need to declare " + appOpPermission
25618                        + " to call this api");
25619            } else {
25620                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25621                return false;
25622            }
25623        }
25624        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25625            return false;
25626        }
25627        if (mExternalSourcesPolicy != null) {
25628            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25629            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25630                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25631            }
25632        }
25633        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25634    }
25635
25636    @Override
25637    public ComponentName getInstantAppResolverSettingsComponent() {
25638        return mInstantAppResolverSettingsComponent;
25639    }
25640
25641    @Override
25642    public ComponentName getInstantAppInstallerComponent() {
25643        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25644            return null;
25645        }
25646        return mInstantAppInstallerActivity == null
25647                ? null : mInstantAppInstallerActivity.getComponentName();
25648    }
25649
25650    @Override
25651    public String getInstantAppAndroidId(String packageName, int userId) {
25652        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25653                "getInstantAppAndroidId");
25654        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25655                true /* requireFullPermission */, false /* checkShell */,
25656                "getInstantAppAndroidId");
25657        // Make sure the target is an Instant App.
25658        if (!isInstantApp(packageName, userId)) {
25659            return null;
25660        }
25661        synchronized (mPackages) {
25662            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25663        }
25664    }
25665
25666    boolean canHaveOatDir(String packageName) {
25667        synchronized (mPackages) {
25668            PackageParser.Package p = mPackages.get(packageName);
25669            if (p == null) {
25670                return false;
25671            }
25672            return p.canHaveOatDir();
25673        }
25674    }
25675
25676    private String getOatDir(PackageParser.Package pkg) {
25677        if (!pkg.canHaveOatDir()) {
25678            return null;
25679        }
25680        File codePath = new File(pkg.codePath);
25681        if (codePath.isDirectory()) {
25682            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25683        }
25684        return null;
25685    }
25686
25687    void deleteOatArtifactsOfPackage(String packageName) {
25688        final String[] instructionSets;
25689        final List<String> codePaths;
25690        final String oatDir;
25691        final PackageParser.Package pkg;
25692        synchronized (mPackages) {
25693            pkg = mPackages.get(packageName);
25694        }
25695        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25696        codePaths = pkg.getAllCodePaths();
25697        oatDir = getOatDir(pkg);
25698
25699        for (String codePath : codePaths) {
25700            for (String isa : instructionSets) {
25701                try {
25702                    mInstaller.deleteOdex(codePath, isa, oatDir);
25703                } catch (InstallerException e) {
25704                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25705                }
25706            }
25707        }
25708    }
25709
25710    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25711        Set<String> unusedPackages = new HashSet<>();
25712        long currentTimeInMillis = System.currentTimeMillis();
25713        synchronized (mPackages) {
25714            for (PackageParser.Package pkg : mPackages.values()) {
25715                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25716                if (ps == null) {
25717                    continue;
25718                }
25719                PackageDexUsage.PackageUseInfo packageUseInfo =
25720                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25721                if (PackageManagerServiceUtils
25722                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25723                                downgradeTimeThresholdMillis, packageUseInfo,
25724                                pkg.getLatestPackageUseTimeInMills(),
25725                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25726                    unusedPackages.add(pkg.packageName);
25727                }
25728            }
25729        }
25730        return unusedPackages;
25731    }
25732}
25733
25734interface PackageSender {
25735    void sendPackageBroadcast(final String action, final String pkg,
25736        final Bundle extras, final int flags, final String targetPkg,
25737        final IIntentReceiver finishedReceiver, final int[] userIds);
25738    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25739        boolean includeStopped, int appId, int... userIds);
25740}
25741